miniz.c 221 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916
  1. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
  2. See "unlicense" statement at the end of this file.
  3. Rich Geldreich <[email protected]>, last updated Oct. 13, 2013
  4. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
  5. Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
  6. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
  7. * Change History
  8. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):
  9. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks [email protected]) which could cause locate files to not find files. This bug
  10. would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()
  11. (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).
  12. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size
  13. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.
  14. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).
  15. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes
  16. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  17. - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.
  18. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  19. - Merged MZ_FORCEINLINE fix from hdeanclark
  20. - Fix <time.h> include before config #ifdef, thanks emil.brink
  21. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can
  22. set it to 1 for real-time compression).
  23. - Merged in some compiler fixes from paulharris's github repro.
  24. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3.
  25. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.
  26. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  27. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled
  28. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch
  29. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
  30. 5/19/12 v1.13 - From [email protected] and [email protected] - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  31. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.
  32. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  33. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly
  34. "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).
  35. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.
  36. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.
  37. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.
  38. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)
  39. - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).
  40. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.
  41. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <[email protected]> for the feedback/bug report.
  42. 5/28/11 v1.11 - Added statement from unlicense.org
  43. 5/27/11 v1.10 - Substantial compressor optimizations:
  44. - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a
  45. - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).
  46. - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.
  47. - Refactored the compression code for better readability and maintainability.
  48. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large
  49. drop in throughput on some files).
  50. 5/15/11 v1.09 - Initial stable release.
  51. * Low-level Deflate/Inflate implementation notes:
  52. Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
  53. greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
  54. approximately as well as zlib.
  55. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
  56. coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
  57. block large enough to hold the entire file.
  58. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
  59. * zlib-style API notes:
  60. miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
  61. zlib replacement in many apps:
  62. The z_stream struct, optional memory allocation callbacks
  63. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  64. inflateInit/inflateInit2/inflate/inflateEnd
  65. compress, compress2, compressBound, uncompress
  66. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
  67. Supports raw deflate streams or standard zlib streams with adler-32 checking.
  68. Limitations:
  69. The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
  70. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
  71. there are no guarantees that miniz.c pulls this off perfectly.
  72. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
  73. Alex Evans. Supports 1-4 bytes/pixel images.
  74. * ZIP archive API notes:
  75. The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
  76. get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
  77. existing archives, create new archives, append new files to existing archives, or clone archive data from
  78. one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
  79. or you can specify custom file read/write callbacks.
  80. - Archive reading: Just call this function to read a single file from a disk archive:
  81. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
  82. size_t *pSize, mz_uint zip_flags);
  83. For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
  84. directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
  85. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
  86. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  87. The locate operation can optionally check file comments too, which (as one example) can be used to identify
  88. multiple versions of the same file in an archive. This function uses a simple linear search through the central
  89. directory, so it's not very fast.
  90. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
  91. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  92. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
  93. to disk and builds an exact image of the central directory in memory. The central directory image is written
  94. all at once at the end of the archive file when the archive is finalized.
  95. The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
  96. which can be useful when the archive will be read from optical media. Also, the writer supports placing
  97. arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
  98. readable by any ZIP tool.
  99. - Archive appending: The simple way to add a single file to an archive is to call this function:
  100. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
  101. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  102. The archive will be created if it doesn't already exist, otherwise it'll be appended to.
  103. Note the appending is done in-place and is not an atomic operation, so if something goes wrong
  104. during the operation it's possible the archive could be left without a central directory (although the local
  105. file headers and file data will be fine, so the archive will be recoverable).
  106. For more complex archive modification scenarios:
  107. 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
  108. preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
  109. compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
  110. you're done. This is safe but requires a bunch of temporary disk space or heap memory.
  111. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
  112. append new files as needed, then finalize the archive which will write an updated central directory to the
  113. original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  114. possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
  115. - ZIP archive support limitations:
  116. No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
  117. Requires streams capable of seeking.
  118. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
  119. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
  120. * Important: For best perf. be sure to customize the below macros for your target platform:
  121. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  122. #define MINIZ_LITTLE_ENDIAN 1
  123. #define MINIZ_HAS_64BIT_REGISTERS 1
  124. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
  125. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
  126. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  127. */
  128. #ifndef MINIZ_HEADER_INCLUDED
  129. #define MINIZ_HEADER_INCLUDED
  130. #include <stdlib.h>
  131. // Defines to completely disable specific portions of miniz.c:
  132. // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
  133. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
  134. //#define MINIZ_NO_STDIO
  135. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
  136. // get/set file times, and the C run-time funcs that get/set times won't be called.
  137. // The current downside is the times written to your archives will be from 1979.
  138. //#define MINIZ_NO_TIME
  139. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  140. //#define MINIZ_NO_ARCHIVE_APIS
  141. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
  142. //#define MINIZ_NO_ARCHIVE_WRITING_APIS
  143. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
  144. //#define MINIZ_NO_ZLIB_APIS
  145. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
  146. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  147. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  148. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
  149. // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
  150. // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
  151. //#define MINIZ_NO_MALLOC
  152. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  153. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
  154. #define MINIZ_NO_TIME
  155. #endif
  156. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  157. #include <time.h>
  158. #endif
  159. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
  160. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  161. #define MINIZ_X86_OR_X64_CPU 1
  162. #endif
  163. #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  164. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  165. #define MINIZ_LITTLE_ENDIAN 1
  166. #endif
  167. #if MINIZ_X86_OR_X64_CPU
  168. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
  169. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  170. #endif
  171. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
  172. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).
  173. #define MINIZ_HAS_64BIT_REGISTERS 1
  174. #endif
  175. #ifdef __cplusplus
  176. extern "C" {
  177. #endif
  178. // ------------------- zlib-style API Definitions.
  179. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  180. typedef unsigned long mz_ulong;
  181. // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
  182. void mz_free(void *p);
  183. #define MZ_ADLER32_INIT (1)
  184. // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
  185. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  186. #define MZ_CRC32_INIT (0)
  187. // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
  188. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  189. // Compression strategies.
  190. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
  191. // Method
  192. #define MZ_DEFLATED 8
  193. #ifndef MINIZ_NO_ZLIB_APIS
  194. // Heap allocation callbacks.
  195. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
  196. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  197. typedef void (*mz_free_func)(void *opaque, void *address);
  198. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
  199. #define MZ_VERSION "9.1.15"
  200. #define MZ_VERNUM 0x91F0
  201. #define MZ_VER_MAJOR 9
  202. #define MZ_VER_MINOR 1
  203. #define MZ_VER_REVISION 15
  204. #define MZ_VER_SUBREVISION 0
  205. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
  206. enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
  207. // Return status codes. MZ_PARAM_ERROR is non-standard.
  208. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
  209. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  210. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };
  211. // Window bits
  212. #define MZ_DEFAULT_WINDOW_BITS 15
  213. struct mz_internal_state;
  214. // Compression/decompression stream struct.
  215. typedef struct mz_stream_s
  216. {
  217. const unsigned char *next_in; // pointer to next byte to read
  218. unsigned int avail_in; // number of bytes available at next_in
  219. mz_ulong total_in; // total number of bytes consumed so far
  220. unsigned char *next_out; // pointer to next byte to write
  221. unsigned int avail_out; // number of bytes that can be written to next_out
  222. mz_ulong total_out; // total number of bytes produced so far
  223. char *msg; // error msg (unused)
  224. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  225. mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
  226. mz_free_func zfree; // optional heap free function (defaults to free)
  227. void *opaque; // heap alloc function user pointer
  228. int data_type; // data_type (unused)
  229. mz_ulong adler; // adler32 of the source or uncompressed data
  230. mz_ulong reserved; // not used
  231. } mz_stream;
  232. typedef mz_stream *mz_streamp;
  233. // Returns the version string of miniz.c.
  234. const char *mz_version(void);
  235. // mz_deflateInit() initializes a compressor with default options:
  236. // Parameters:
  237. // pStream must point to an initialized mz_stream struct.
  238. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  239. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
  240. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  241. // Return values:
  242. // MZ_OK on success.
  243. // MZ_STREAM_ERROR if the stream is bogus.
  244. // MZ_PARAM_ERROR if the input parameters are bogus.
  245. // MZ_MEM_ERROR on out of memory.
  246. int mz_deflateInit(mz_streamp pStream, int level);
  247. // mz_deflateInit2() is like mz_deflate(), except with more control:
  248. // Additional parameters:
  249. // method must be MZ_DEFLATED
  250. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
  251. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  252. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
  253. // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  254. int mz_deflateReset(mz_streamp pStream);
  255. // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
  256. // Parameters:
  257. // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  258. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
  259. // Return values:
  260. // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
  261. // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
  262. // MZ_STREAM_ERROR if the stream is bogus.
  263. // MZ_PARAM_ERROR if one of the parameters is invalid.
  264. // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
  265. int mz_deflate(mz_streamp pStream, int flush);
  266. // mz_deflateEnd() deinitializes a compressor:
  267. // Return values:
  268. // MZ_OK on success.
  269. // MZ_STREAM_ERROR if the stream is bogus.
  270. int mz_deflateEnd(mz_streamp pStream);
  271. // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
  272. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  273. // Single-call compression functions mz_compress() and mz_compress2():
  274. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
  275. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  276. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
  277. // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
  278. mz_ulong mz_compressBound(mz_ulong source_len);
  279. // Initializes a decompressor.
  280. int mz_inflateInit(mz_streamp pStream);
  281. // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
  282. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  283. int mz_inflateInit2(mz_streamp pStream, int window_bits);
  284. // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
  285. // Parameters:
  286. // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  287. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  288. // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
  289. // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
  290. // Return values:
  291. // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
  292. // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
  293. // MZ_STREAM_ERROR if the stream is bogus.
  294. // MZ_DATA_ERROR if the deflate stream is invalid.
  295. // MZ_PARAM_ERROR if one of the parameters is invalid.
  296. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
  297. // with more input data, or with more room in the output buffer (except when using single call decompression, described above).
  298. int mz_inflate(mz_streamp pStream, int flush);
  299. // Deinitializes a decompressor.
  300. int mz_inflateEnd(mz_streamp pStream);
  301. // Single-call decompression.
  302. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
  303. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  304. // Returns a string description of the specified error code, or NULL if the error code is invalid.
  305. const char *mz_error(int err);
  306. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
  307. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
  308. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  309. typedef unsigned char Byte;
  310. typedef unsigned int uInt;
  311. typedef mz_ulong uLong;
  312. typedef Byte Bytef;
  313. typedef uInt uIntf;
  314. typedef char charf;
  315. typedef int intf;
  316. typedef void *voidpf;
  317. typedef uLong uLongf;
  318. typedef void *voidp;
  319. typedef void *const voidpc;
  320. #define Z_NULL 0
  321. #define Z_NO_FLUSH MZ_NO_FLUSH
  322. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  323. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  324. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  325. #define Z_FINISH MZ_FINISH
  326. #define Z_BLOCK MZ_BLOCK
  327. #define Z_OK MZ_OK
  328. #define Z_STREAM_END MZ_STREAM_END
  329. #define Z_NEED_DICT MZ_NEED_DICT
  330. #define Z_ERRNO MZ_ERRNO
  331. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  332. #define Z_DATA_ERROR MZ_DATA_ERROR
  333. #define Z_MEM_ERROR MZ_MEM_ERROR
  334. #define Z_BUF_ERROR MZ_BUF_ERROR
  335. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  336. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  337. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  338. #define Z_BEST_SPEED MZ_BEST_SPEED
  339. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  340. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  341. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  342. #define Z_FILTERED MZ_FILTERED
  343. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  344. #define Z_RLE MZ_RLE
  345. #define Z_FIXED MZ_FIXED
  346. #define Z_DEFLATED MZ_DEFLATED
  347. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  348. #define alloc_func mz_alloc_func
  349. #define free_func mz_free_func
  350. #define internal_state mz_internal_state
  351. #define z_stream mz_stream
  352. #define deflateInit mz_deflateInit
  353. #define deflateInit2 mz_deflateInit2
  354. #define deflateReset mz_deflateReset
  355. #define deflate mz_deflate
  356. #define deflateEnd mz_deflateEnd
  357. #define deflateBound mz_deflateBound
  358. #define compress mz_compress
  359. #define compress2 mz_compress2
  360. #define compressBound mz_compressBound
  361. #define inflateInit mz_inflateInit
  362. #define inflateInit2 mz_inflateInit2
  363. #define inflate mz_inflate
  364. #define inflateEnd mz_inflateEnd
  365. #define uncompress mz_uncompress
  366. #define crc32 mz_crc32
  367. #define adler32 mz_adler32
  368. #define MAX_WBITS 15
  369. #define MAX_MEM_LEVEL 9
  370. #define zError mz_error
  371. #define ZLIB_VERSION MZ_VERSION
  372. #define ZLIB_VERNUM MZ_VERNUM
  373. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  374. #define ZLIB_VER_MINOR MZ_VER_MINOR
  375. #define ZLIB_VER_REVISION MZ_VER_REVISION
  376. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  377. #define zlibVersion mz_version
  378. #define zlib_version mz_version()
  379. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  380. #endif // MINIZ_NO_ZLIB_APIS
  381. // ------------------- Types and macros
  382. typedef unsigned char mz_uint8;
  383. typedef signed short mz_int16;
  384. typedef unsigned short mz_uint16;
  385. typedef unsigned int mz_uint32;
  386. typedef unsigned int mz_uint;
  387. typedef long long mz_int64;
  388. typedef unsigned long long mz_uint64;
  389. typedef int mz_bool;
  390. #define MZ_FALSE (0)
  391. #define MZ_TRUE (1)
  392. // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
  393. #ifdef _MSC_VER
  394. #define MZ_MACRO_END while (0, 0)
  395. #else
  396. #define MZ_MACRO_END while (0)
  397. #endif
  398. // ------------------- ZIP archive reading/writing
  399. #ifndef MINIZ_NO_ARCHIVE_APIS
  400. enum
  401. {
  402. MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,
  403. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  404. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  405. };
  406. typedef struct
  407. {
  408. mz_uint32 m_file_index;
  409. mz_uint32 m_central_dir_ofs;
  410. mz_uint16 m_version_made_by;
  411. mz_uint16 m_version_needed;
  412. mz_uint16 m_bit_flag;
  413. mz_uint16 m_method;
  414. #ifndef MINIZ_NO_TIME
  415. time_t m_time;
  416. #endif
  417. mz_uint32 m_crc32;
  418. mz_uint64 m_comp_size;
  419. mz_uint64 m_uncomp_size;
  420. mz_uint16 m_internal_attr;
  421. mz_uint32 m_external_attr;
  422. mz_uint64 m_local_header_ofs;
  423. mz_uint32 m_comment_size;
  424. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  425. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  426. } mz_zip_archive_file_stat;
  427. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
  428. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
  429. struct mz_zip_internal_state_tag;
  430. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  431. typedef enum
  432. {
  433. MZ_ZIP_MODE_INVALID = 0,
  434. MZ_ZIP_MODE_READING = 1,
  435. MZ_ZIP_MODE_WRITING = 2,
  436. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  437. } mz_zip_mode;
  438. typedef struct mz_zip_archive_tag
  439. {
  440. mz_uint64 m_archive_size;
  441. mz_uint64 m_central_directory_file_ofs;
  442. mz_uint m_total_files;
  443. mz_zip_mode m_zip_mode;
  444. mz_uint m_file_offset_alignment;
  445. mz_alloc_func m_pAlloc;
  446. mz_free_func m_pFree;
  447. mz_realloc_func m_pRealloc;
  448. void *m_pAlloc_opaque;
  449. mz_file_read_func m_pRead;
  450. mz_file_write_func m_pWrite;
  451. void *m_pIO_opaque;
  452. mz_zip_internal_state *m_pState;
  453. } mz_zip_archive;
  454. typedef enum
  455. {
  456. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  457. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  458. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  459. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  460. } mz_zip_flags;
  461. // ZIP archive reading
  462. // Inits a ZIP archive reader.
  463. // These functions read and validate the archive's central directory.
  464. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
  465. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
  466. #ifndef MINIZ_NO_STDIO
  467. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
  468. #endif
  469. // Returns the total number of files in the archive.
  470. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  471. // Returns detailed information about an archive file entry.
  472. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
  473. // Determines if an archive file entry is a directory entry.
  474. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
  475. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
  476. // Retrieves the filename of an archive file entry.
  477. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
  478. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
  479. // Attempts to locates a file in the archive's central directory.
  480. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  481. // Returns -1 if the file cannot be found.
  482. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  483. // Extracts a archive file to a memory buffer using no memory allocation.
  484. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  485. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  486. // Extracts a archive file to a memory buffer.
  487. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
  488. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
  489. // Extracts a archive file to a dynamically allocated heap buffer.
  490. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
  491. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
  492. // Extracts a archive file using a callback function to output the file's data.
  493. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  494. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  495. #ifndef MINIZ_NO_STDIO
  496. // Extracts a archive file to a disk file and sets its last accessed and modified times.
  497. // This function only extracts files, not archive directory records.
  498. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
  499. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
  500. #endif
  501. // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
  502. mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  503. // ZIP archive writing
  504. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  505. // Inits a ZIP archive writer.
  506. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  507. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
  508. #ifndef MINIZ_NO_STDIO
  509. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
  510. #endif
  511. // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
  512. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
  513. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
  514. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
  515. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
  516. // the archive is finalized the file's central directory will be hosed.
  517. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
  518. // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
  519. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
  520. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  521. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
  522. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
  523. #ifndef MINIZ_NO_STDIO
  524. // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
  525. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  526. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  527. #endif
  528. // Adds a file to an archive by fully cloning the data from another archive.
  529. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
  530. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
  531. // Finalizes the archive by writing the central directory records followed by the end of central directory record.
  532. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
  533. // An archive must be manually finalized by calling this function for it to be valid.
  534. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  535. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
  536. // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
  537. // Note for the archive to be valid, it must have been finalized before ending.
  538. mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  539. // Misc. high-level helper functions:
  540. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
  541. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  542. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  543. // Reads a single file from an archive into a heap block.
  544. // Returns NULL on failure.
  545. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
  546. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  547. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  548. // ------------------- Low-level Decompression API Definitions
  549. // Decompression flags used by tinfl_decompress().
  550. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
  551. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
  552. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
  553. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
  554. enum
  555. {
  556. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  557. TINFL_FLAG_HAS_MORE_INPUT = 2,
  558. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  559. TINFL_FLAG_COMPUTE_ADLER32 = 8
  560. };
  561. // High level decompression functions:
  562. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
  563. // On entry:
  564. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
  565. // On return:
  566. // Function returns a pointer to the decompressed data, or NULL on failure.
  567. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
  568. // The caller must call mz_free() on the returned block when it's no longer needed.
  569. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  570. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
  571. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
  572. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  573. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  574. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
  575. // Returns 1 on success or 0 on failure.
  576. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  577. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  578. struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
  579. // Max size of LZ dictionary.
  580. #define TINFL_LZ_DICT_SIZE 32768
  581. // Return status.
  582. typedef enum
  583. {
  584. TINFL_STATUS_BAD_PARAM = -3,
  585. TINFL_STATUS_ADLER32_MISMATCH = -2,
  586. TINFL_STATUS_FAILED = -1,
  587. TINFL_STATUS_DONE = 0,
  588. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  589. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  590. } tinfl_status;
  591. // Initializes the decompressor to its initial state.
  592. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
  593. #define tinfl_get_adler32(r) (r)->m_check_adler32
  594. // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
  595. // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
  596. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
  597. // Internal/private bits follow.
  598. enum
  599. {
  600. TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  601. TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  602. };
  603. typedef struct
  604. {
  605. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  606. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  607. } tinfl_huff_table;
  608. #if MINIZ_HAS_64BIT_REGISTERS
  609. #define TINFL_USE_64BIT_BITBUF 1
  610. #endif
  611. #if TINFL_USE_64BIT_BITBUF
  612. typedef mz_uint64 tinfl_bit_buf_t;
  613. #define TINFL_BITBUF_SIZE (64)
  614. #else
  615. typedef mz_uint32 tinfl_bit_buf_t;
  616. #define TINFL_BITBUF_SIZE (32)
  617. #endif
  618. struct tinfl_decompressor_tag
  619. {
  620. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
  621. tinfl_bit_buf_t m_bit_buf;
  622. size_t m_dist_from_out_buf_start;
  623. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  624. mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  625. };
  626. // ------------------- Low-level Compression API Definitions
  627. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
  628. #define TDEFL_LESS_MEMORY 0
  629. // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
  630. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).
  631. enum
  632. {
  633. TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
  634. };
  635. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.
  636. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
  637. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
  638. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).
  639. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  640. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  641. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  642. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  643. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  644. enum
  645. {
  646. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  647. TDEFL_COMPUTE_ADLER32 = 0x02000,
  648. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  649. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  650. TDEFL_RLE_MATCHES = 0x10000,
  651. TDEFL_FILTER_MATCHES = 0x20000,
  652. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  653. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  654. };
  655. // High level compression functions:
  656. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
  657. // On entry:
  658. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  659. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
  660. // On return:
  661. // Function returns a pointer to the compressed data, or NULL on failure.
  662. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
  663. // The caller must free() the returned block when it's no longer needed.
  664. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  665. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
  666. // Returns 0 on failure.
  667. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  668. // Compresses an image to a compressed PNG file in memory.
  669. // On entry:
  670. // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
  671. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
  672. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  673. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
  674. // On return:
  675. // Function returns a pointer to the compressed data, or NULL on failure.
  676. // *pLen_out will be set to the size of the PNG image file.
  677. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
  678. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);
  679. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);
  680. // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  681. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  682. // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
  683. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  684. enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
  685. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
  686. #if TDEFL_LESS_MEMORY
  687. enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  688. #else
  689. enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  690. #endif
  691. // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
  692. typedef enum
  693. {
  694. TDEFL_STATUS_BAD_PARAM = -2,
  695. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  696. TDEFL_STATUS_OKAY = 0,
  697. TDEFL_STATUS_DONE = 1,
  698. } tdefl_status;
  699. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  700. typedef enum
  701. {
  702. TDEFL_NO_FLUSH = 0,
  703. TDEFL_SYNC_FLUSH = 2,
  704. TDEFL_FULL_FLUSH = 3,
  705. TDEFL_FINISH = 4
  706. } tdefl_flush;
  707. // tdefl's compression state structure.
  708. typedef struct
  709. {
  710. tdefl_put_buf_func_ptr m_pPut_buf_func;
  711. void *m_pPut_buf_user;
  712. mz_uint m_flags, m_max_probes[2];
  713. int m_greedy_parsing;
  714. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  715. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  716. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
  717. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
  718. tdefl_status m_prev_return_status;
  719. const void *m_pIn_buf;
  720. void *m_pOut_buf;
  721. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  722. tdefl_flush m_flush;
  723. const mz_uint8 *m_pSrc;
  724. size_t m_src_buf_left, m_out_buf_ofs;
  725. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  726. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  727. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  728. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  729. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  730. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  731. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  732. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  733. } tdefl_compressor;
  734. // Initializes the compressor.
  735. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
  736. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
  737. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
  738. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
  739. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  740. // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.
  741. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
  742. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
  743. // tdefl_compress_buffer() always consumes the entire input buffer.
  744. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
  745. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  746. mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  747. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
  748. #ifndef MINIZ_NO_ZLIB_APIS
  749. // Create tdefl_compress() flags given zlib-style compression parameters.
  750. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
  751. // window_bits may be -15 (raw deflate) or 15 (zlib)
  752. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
  753. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
  754. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  755. #ifdef __cplusplus
  756. }
  757. #endif
  758. #endif // MINIZ_HEADER_INCLUDED
  759. // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
  760. #ifndef MINIZ_HEADER_FILE_ONLY
  761. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
  762. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
  763. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
  764. #include <string.h>
  765. #include <assert.h>
  766. #define MZ_ASSERT(x) assert(x)
  767. #ifdef MINIZ_NO_MALLOC
  768. #define MZ_MALLOC(x) NULL
  769. #define MZ_FREE(x) (void)x, ((void)0)
  770. #define MZ_REALLOC(p, x) NULL
  771. #else
  772. #define MZ_MALLOC(x) malloc(x)
  773. #define MZ_FREE(x) free(x)
  774. #define MZ_REALLOC(p, x) realloc(p, x)
  775. #endif
  776. #define MZ_MAX(a,b) (((a)>(b))?(a):(b))
  777. #define MZ_MIN(a,b) (((a)<(b))?(a):(b))
  778. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  779. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  780. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  781. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  782. #else
  783. #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  784. #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  785. #endif
  786. #ifdef _MSC_VER
  787. #define MZ_FORCEINLINE __forceinline
  788. #elif defined(__GNUC__)
  789. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  790. #else
  791. #define MZ_FORCEINLINE inline
  792. #endif
  793. #ifdef __cplusplus
  794. extern "C" {
  795. #endif
  796. // ------------------- zlib-style API's
  797. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)
  798. {
  799. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552;
  800. if (!ptr) return MZ_ADLER32_INIT;
  801. while (buf_len) {
  802. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  803. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  804. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  805. }
  806. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  807. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  808. }
  809. return (s2 << 16) + s1;
  810. }
  811. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
  812. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
  813. {
  814. static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
  815. 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
  816. mz_uint32 crcu32 = (mz_uint32)crc;
  817. if (!ptr) return MZ_CRC32_INIT;
  818. crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; }
  819. return ~crcu32;
  820. }
  821. void mz_free(void *p)
  822. {
  823. MZ_FREE(p);
  824. }
  825. #ifndef MINIZ_NO_ZLIB_APIS
  826. static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); }
  827. static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); }
  828. static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); }
  829. const char *mz_version(void)
  830. {
  831. return MZ_VERSION;
  832. }
  833. int mz_deflateInit(mz_streamp pStream, int level)
  834. {
  835. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);
  836. }
  837. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)
  838. {
  839. tdefl_compressor *pComp;
  840. mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  841. if (!pStream) return MZ_STREAM_ERROR;
  842. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR;
  843. pStream->data_type = 0;
  844. pStream->adler = MZ_ADLER32_INIT;
  845. pStream->msg = NULL;
  846. pStream->reserved = 0;
  847. pStream->total_in = 0;
  848. pStream->total_out = 0;
  849. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  850. if (!pStream->zfree) pStream->zfree = def_free_func;
  851. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));
  852. if (!pComp)
  853. return MZ_MEM_ERROR;
  854. pStream->state = (struct mz_internal_state *)pComp;
  855. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)
  856. {
  857. mz_deflateEnd(pStream);
  858. return MZ_PARAM_ERROR;
  859. }
  860. return MZ_OK;
  861. }
  862. int mz_deflateReset(mz_streamp pStream)
  863. {
  864. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR;
  865. pStream->total_in = pStream->total_out = 0;
  866. tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags);
  867. return MZ_OK;
  868. }
  869. int mz_deflate(mz_streamp pStream, int flush)
  870. {
  871. size_t in_bytes, out_bytes;
  872. mz_ulong orig_total_in, orig_total_out;
  873. int mz_status = MZ_OK;
  874. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR;
  875. if (!pStream->avail_out) return MZ_BUF_ERROR;
  876. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  877. if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)
  878. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  879. orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
  880. for ( ; ; )
  881. {
  882. tdefl_status defl_status;
  883. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  884. defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);
  885. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  886. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state);
  887. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
  888. pStream->total_out += (mz_uint)out_bytes;
  889. if (defl_status < 0)
  890. {
  891. mz_status = MZ_STREAM_ERROR;
  892. break;
  893. }
  894. else if (defl_status == TDEFL_STATUS_DONE)
  895. {
  896. mz_status = MZ_STREAM_END;
  897. break;
  898. }
  899. else if (!pStream->avail_out)
  900. break;
  901. else if ((!pStream->avail_in) && (flush != MZ_FINISH))
  902. {
  903. if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))
  904. break;
  905. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  906. }
  907. }
  908. return mz_status;
  909. }
  910. int mz_deflateEnd(mz_streamp pStream)
  911. {
  912. if (!pStream) return MZ_STREAM_ERROR;
  913. if (pStream->state)
  914. {
  915. pStream->zfree(pStream->opaque, pStream->state);
  916. pStream->state = NULL;
  917. }
  918. return MZ_OK;
  919. }
  920. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)
  921. {
  922. (void)pStream;
  923. // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
  924. return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  925. }
  926. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)
  927. {
  928. int status;
  929. mz_stream stream;
  930. memset(&stream, 0, sizeof(stream));
  931. // In case mz_ulong is 64-bits (argh I hate longs).
  932. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  933. stream.next_in = pSource;
  934. stream.avail_in = (mz_uint32)source_len;
  935. stream.next_out = pDest;
  936. stream.avail_out = (mz_uint32)*pDest_len;
  937. status = mz_deflateInit(&stream, level);
  938. if (status != MZ_OK) return status;
  939. status = mz_deflate(&stream, MZ_FINISH);
  940. if (status != MZ_STREAM_END)
  941. {
  942. mz_deflateEnd(&stream);
  943. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  944. }
  945. *pDest_len = stream.total_out;
  946. return mz_deflateEnd(&stream);
  947. }
  948. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  949. {
  950. return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);
  951. }
  952. mz_ulong mz_compressBound(mz_ulong source_len)
  953. {
  954. return mz_deflateBound(NULL, source_len);
  955. }
  956. typedef struct
  957. {
  958. tinfl_decompressor m_decomp;
  959. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
  960. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  961. tinfl_status m_last_status;
  962. } inflate_state;
  963. int mz_inflateInit2(mz_streamp pStream, int window_bits)
  964. {
  965. inflate_state *pDecomp;
  966. if (!pStream) return MZ_STREAM_ERROR;
  967. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR;
  968. pStream->data_type = 0;
  969. pStream->adler = 0;
  970. pStream->msg = NULL;
  971. pStream->total_in = 0;
  972. pStream->total_out = 0;
  973. pStream->reserved = 0;
  974. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  975. if (!pStream->zfree) pStream->zfree = def_free_func;
  976. pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));
  977. if (!pDecomp) return MZ_MEM_ERROR;
  978. pStream->state = (struct mz_internal_state *)pDecomp;
  979. tinfl_init(&pDecomp->m_decomp);
  980. pDecomp->m_dict_ofs = 0;
  981. pDecomp->m_dict_avail = 0;
  982. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  983. pDecomp->m_first_call = 1;
  984. pDecomp->m_has_flushed = 0;
  985. pDecomp->m_window_bits = window_bits;
  986. return MZ_OK;
  987. }
  988. int mz_inflateInit(mz_streamp pStream)
  989. {
  990. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  991. }
  992. int mz_inflate(mz_streamp pStream, int flush)
  993. {
  994. inflate_state* pState;
  995. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  996. size_t in_bytes, out_bytes, orig_avail_in;
  997. tinfl_status status;
  998. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  999. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1000. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1001. pState = (inflate_state*)pStream->state;
  1002. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1003. orig_avail_in = pStream->avail_in;
  1004. first_call = pState->m_first_call; pState->m_first_call = 0;
  1005. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1006. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1007. pState->m_has_flushed |= (flush == MZ_FINISH);
  1008. if ((flush == MZ_FINISH) && (first_call))
  1009. {
  1010. // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
  1011. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1012. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  1013. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);
  1014. pState->m_last_status = status;
  1015. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
  1016. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1017. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
  1018. if (status < 0)
  1019. return MZ_DATA_ERROR;
  1020. else if (status != TINFL_STATUS_DONE)
  1021. {
  1022. pState->m_last_status = TINFL_STATUS_FAILED;
  1023. return MZ_BUF_ERROR;
  1024. }
  1025. return MZ_STREAM_END;
  1026. }
  1027. // flush != MZ_FINISH then we must assume there's more input.
  1028. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1029. if (pState->m_dict_avail)
  1030. {
  1031. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1032. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1033. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1034. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1035. return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1036. }
  1037. for ( ; ; )
  1038. {
  1039. in_bytes = pStream->avail_in;
  1040. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1041. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1042. pState->m_last_status = status;
  1043. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  1044. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1045. pState->m_dict_avail = (mz_uint)out_bytes;
  1046. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1047. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1048. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1049. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1050. if (status < 0)
  1051. return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
  1052. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1053. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
  1054. else if (flush == MZ_FINISH)
  1055. {
  1056. // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
  1057. if (status == TINFL_STATUS_DONE)
  1058. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1059. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong.
  1060. else if (!pStream->avail_out)
  1061. return MZ_BUF_ERROR;
  1062. }
  1063. else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))
  1064. break;
  1065. }
  1066. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1067. }
  1068. int mz_inflateEnd(mz_streamp pStream)
  1069. {
  1070. if (!pStream)
  1071. return MZ_STREAM_ERROR;
  1072. if (pStream->state)
  1073. {
  1074. pStream->zfree(pStream->opaque, pStream->state);
  1075. pStream->state = NULL;
  1076. }
  1077. return MZ_OK;
  1078. }
  1079. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  1080. {
  1081. mz_stream stream;
  1082. int status;
  1083. memset(&stream, 0, sizeof(stream));
  1084. // In case mz_ulong is 64-bits (argh I hate longs).
  1085. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1086. stream.next_in = pSource;
  1087. stream.avail_in = (mz_uint32)source_len;
  1088. stream.next_out = pDest;
  1089. stream.avail_out = (mz_uint32)*pDest_len;
  1090. status = mz_inflateInit(&stream);
  1091. if (status != MZ_OK)
  1092. return status;
  1093. status = mz_inflate(&stream, MZ_FINISH);
  1094. if (status != MZ_STREAM_END)
  1095. {
  1096. mz_inflateEnd(&stream);
  1097. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;
  1098. }
  1099. *pDest_len = stream.total_out;
  1100. return mz_inflateEnd(&stream);
  1101. }
  1102. const char *mz_error(int err)
  1103. {
  1104. static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
  1105. {
  1106. { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" },
  1107. { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }
  1108. };
  1109. mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  1110. return NULL;
  1111. }
  1112. #endif //MINIZ_NO_ZLIB_APIS
  1113. // ------------------- Low-level Decompression (completely independent from all compression API's)
  1114. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  1115. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  1116. #define TINFL_CR_BEGIN switch(r->m_state) { case 0:
  1117. #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
  1118. #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
  1119. #define TINFL_CR_FINISH }
  1120. // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
  1121. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
  1122. #define TINFL_GET_BYTE(state_index, c) do { \
  1123. if (pIn_buf_cur >= pIn_buf_end) { \
  1124. for ( ; ; ) { \
  1125. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  1126. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  1127. if (pIn_buf_cur < pIn_buf_end) { \
  1128. c = *pIn_buf_cur++; \
  1129. break; \
  1130. } \
  1131. } else { \
  1132. c = 0; \
  1133. break; \
  1134. } \
  1135. } \
  1136. } else c = *pIn_buf_cur++; } MZ_MACRO_END
  1137. #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
  1138. #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1139. #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1140. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
  1141. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
  1142. // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
  1143. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  1144. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  1145. do { \
  1146. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  1147. if (temp >= 0) { \
  1148. code_len = temp >> 9; \
  1149. if ((code_len) && (num_bits >= code_len)) \
  1150. break; \
  1151. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  1152. code_len = TINFL_FAST_LOOKUP_BITS; \
  1153. do { \
  1154. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  1155. } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \
  1156. } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \
  1157. } while (num_bits < 15);
  1158. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
  1159. // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
  1160. // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
  1161. // The slow path is only executed at the very end of the input buffer.
  1162. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
  1163. int temp; mz_uint code_len, c; \
  1164. if (num_bits < 15) { \
  1165. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  1166. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  1167. } else { \
  1168. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
  1169. } \
  1170. } \
  1171. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
  1172. code_len = temp >> 9, temp &= 511; \
  1173. else { \
  1174. code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
  1175. } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
  1176. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
  1177. {
  1178. static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
  1179. static const int s_length_extra[31]= { 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,0,0 };
  1180. static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1181. static const int s_dist_extra[32] = { 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};
  1182. static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  1183. static const int s_min_table_sizes[3] = { 257, 1, 4 };
  1184. tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
  1185. const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  1186. mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  1187. size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
  1188. // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
  1189. if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
  1190. num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  1191. TINFL_CR_BEGIN
  1192. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
  1193. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1194. {
  1195. TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);
  1196. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  1197. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
  1198. if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }
  1199. }
  1200. do
  1201. {
  1202. TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;
  1203. if (r->m_type == 0)
  1204. {
  1205. TINFL_SKIP_BITS(5, num_bits & 7);
  1206. for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); }
  1207. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); }
  1208. while ((counter) && (num_bits))
  1209. {
  1210. TINFL_GET_BITS(51, dist, 8);
  1211. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1212. *pOut_buf_cur++ = (mz_uint8)dist;
  1213. counter--;
  1214. }
  1215. while (counter)
  1216. {
  1217. size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1218. while (pIn_buf_cur >= pIn_buf_end)
  1219. {
  1220. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
  1221. {
  1222. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  1223. }
  1224. else
  1225. {
  1226. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  1227. }
  1228. }
  1229. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
  1230. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
  1231. }
  1232. }
  1233. else if (r->m_type == 3)
  1234. {
  1235. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  1236. }
  1237. else
  1238. {
  1239. if (r->m_type == 1)
  1240. {
  1241. mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
  1242. r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  1243. for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8;
  1244. }
  1245. else
  1246. {
  1247. for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
  1248. MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
  1249. r->m_table_sizes[2] = 19;
  1250. }
  1251. for ( ; (int)r->m_type >= 0; r->m_type--)
  1252. {
  1253. int tree_next, tree_cur; tinfl_huff_table *pTable;
  1254. mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree);
  1255. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
  1256. used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
  1257. for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }
  1258. if ((65536 != total) && (used_syms > 1))
  1259. {
  1260. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  1261. }
  1262. for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
  1263. {
  1264. mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;
  1265. cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
  1266. if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; }
  1267. if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
  1268. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  1269. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
  1270. {
  1271. tree_cur -= ((rev_code >>= 1) & 1);
  1272. if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];
  1273. }
  1274. tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  1275. }
  1276. if (r->m_type == 2)
  1277. {
  1278. for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
  1279. {
  1280. mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
  1281. if ((dist == 16) && (!counter))
  1282. {
  1283. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  1284. }
  1285. num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];
  1286. TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;
  1287. }
  1288. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
  1289. {
  1290. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  1291. }
  1292. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
  1293. }
  1294. }
  1295. for ( ; ; )
  1296. {
  1297. mz_uint8 *pSrc;
  1298. for ( ; ; )
  1299. {
  1300. if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
  1301. {
  1302. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  1303. if (counter >= 256)
  1304. break;
  1305. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1306. *pOut_buf_cur++ = (mz_uint8)counter;
  1307. }
  1308. else
  1309. {
  1310. int sym2; mz_uint code_len;
  1311. #if TINFL_USE_64BIT_BITBUF
  1312. if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; }
  1313. #else
  1314. if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1315. #endif
  1316. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1317. code_len = sym2 >> 9;
  1318. else
  1319. {
  1320. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1321. }
  1322. counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
  1323. if (counter & 256)
  1324. break;
  1325. #if !TINFL_USE_64BIT_BITBUF
  1326. if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1327. #endif
  1328. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1329. code_len = sym2 >> 9;
  1330. else
  1331. {
  1332. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1333. }
  1334. bit_buf >>= code_len; num_bits -= code_len;
  1335. pOut_buf_cur[0] = (mz_uint8)counter;
  1336. if (sym2 & 256)
  1337. {
  1338. pOut_buf_cur++;
  1339. counter = sym2;
  1340. break;
  1341. }
  1342. pOut_buf_cur[1] = (mz_uint8)sym2;
  1343. pOut_buf_cur += 2;
  1344. }
  1345. }
  1346. if ((counter &= 511) == 256) break;
  1347. num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
  1348. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }
  1349. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  1350. num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
  1351. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }
  1352. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  1353. if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  1354. {
  1355. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  1356. }
  1357. pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  1358. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
  1359. {
  1360. while (counter--)
  1361. {
  1362. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1363. *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
  1364. }
  1365. continue;
  1366. }
  1367. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1368. else if ((counter >= 9) && (counter <= dist))
  1369. {
  1370. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  1371. do
  1372. {
  1373. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  1374. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  1375. pOut_buf_cur += 8;
  1376. } while ((pSrc += 8) < pSrc_end);
  1377. if ((counter &= 7) < 3)
  1378. {
  1379. if (counter)
  1380. {
  1381. pOut_buf_cur[0] = pSrc[0];
  1382. if (counter > 1)
  1383. pOut_buf_cur[1] = pSrc[1];
  1384. pOut_buf_cur += counter;
  1385. }
  1386. continue;
  1387. }
  1388. }
  1389. #endif
  1390. do
  1391. {
  1392. pOut_buf_cur[0] = pSrc[0];
  1393. pOut_buf_cur[1] = pSrc[1];
  1394. pOut_buf_cur[2] = pSrc[2];
  1395. pOut_buf_cur += 3; pSrc += 3;
  1396. } while ((int)(counter -= 3) > 2);
  1397. if ((int)counter > 0)
  1398. {
  1399. pOut_buf_cur[0] = pSrc[0];
  1400. if ((int)counter > 1)
  1401. pOut_buf_cur[1] = pSrc[1];
  1402. pOut_buf_cur += counter;
  1403. }
  1404. }
  1405. }
  1406. } while (!(r->m_final & 1));
  1407. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1408. {
  1409. TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; }
  1410. }
  1411. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  1412. TINFL_CR_FINISH
  1413. common_exit:
  1414. r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  1415. *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  1416. if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
  1417. {
  1418. const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
  1419. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
  1420. while (buf_len)
  1421. {
  1422. for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
  1423. {
  1424. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  1425. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  1426. }
  1427. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1428. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  1429. }
  1430. r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
  1431. }
  1432. return status;
  1433. }
  1434. // Higher level helper functions.
  1435. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  1436. {
  1437. tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
  1438. *pOut_len = 0;
  1439. tinfl_init(&decomp);
  1440. for ( ; ; )
  1441. {
  1442. size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  1443. tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
  1444. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1445. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
  1446. {
  1447. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1448. }
  1449. src_buf_ofs += src_buf_size;
  1450. *pOut_len += dst_buf_size;
  1451. if (status == TINFL_STATUS_DONE) break;
  1452. new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  1453. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  1454. if (!pNew_buf)
  1455. {
  1456. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1457. }
  1458. pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
  1459. }
  1460. return pBuf;
  1461. }
  1462. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  1463. {
  1464. tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);
  1465. status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1466. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
  1467. }
  1468. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  1469. {
  1470. int result = 0;
  1471. tinfl_decompressor decomp;
  1472. mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;
  1473. if (!pDict)
  1474. return TINFL_STATUS_FAILED;
  1475. tinfl_init(&decomp);
  1476. for ( ; ; )
  1477. {
  1478. size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  1479. tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  1480. (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  1481. in_buf_ofs += in_buf_size;
  1482. if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  1483. break;
  1484. if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
  1485. {
  1486. result = (status == TINFL_STATUS_DONE);
  1487. break;
  1488. }
  1489. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  1490. }
  1491. MZ_FREE(pDict);
  1492. *pIn_buf_size = in_buf_ofs;
  1493. return result;
  1494. }
  1495. // ------------------- Low-level Compression (independent from all decompression API's)
  1496. // Purposely making these tables static for faster init and thread safety.
  1497. static const mz_uint16 s_tdefl_len_sym[256] = {
  1498. 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
  1499. 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
  1500. 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
  1501. 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
  1502. 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
  1503. 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
  1504. 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
  1505. 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };
  1506. static const mz_uint8 s_tdefl_len_extra[256] = {
  1507. 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
  1508. 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
  1509. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  1510. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };
  1511. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  1512. 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  1513. 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
  1514. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
  1515. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  1516. 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  1517. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1518. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1519. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1520. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1521. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1522. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1523. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 };
  1524. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  1525. 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
  1526. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1527. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1528. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1529. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1530. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1531. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1532. 7,7,7,7,7,7,7,7 };
  1533. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  1534. 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
  1535. 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
  1536. 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };
  1537. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  1538. 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  1539. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  1540. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 };
  1541. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
  1542. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  1543. static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
  1544. {
  1545. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist);
  1546. for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; }
  1547. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
  1548. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1549. {
  1550. const mz_uint32* pHist = &hist[pass << 8];
  1551. mz_uint offsets[256], cur_ofs = 0;
  1552. for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
  1553. for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1554. { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
  1555. }
  1556. return pCur_syms;
  1557. }
  1558. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, [email protected], Jyrki Katajainen, [email protected], November 1996.
  1559. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
  1560. {
  1561. int root, leaf, next, avbl, used, dpth;
  1562. if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
  1563. A[0].m_key += A[1].m_key; root = 0; leaf = 2;
  1564. for (next=1; next < n-1; next++)
  1565. {
  1566. if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;
  1567. if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  1568. }
  1569. A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
  1570. avbl = 1; used = dpth = 0; root = n-2; next = n-1;
  1571. while (avbl>0)
  1572. {
  1573. while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
  1574. while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; }
  1575. avbl = 2*used; dpth++; used = 0;
  1576. }
  1577. }
  1578. // Limits canonical Huffman code table's max code size.
  1579. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  1580. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  1581. {
  1582. int i; mz_uint32 total = 0; if (code_list_len <= 1) return;
  1583. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
  1584. for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  1585. while (total != (1UL << max_code_size))
  1586. {
  1587. pNum_codes[max_code_size]--;
  1588. for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
  1589. total--;
  1590. }
  1591. }
  1592. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
  1593. {
  1594. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes);
  1595. if (static_table)
  1596. {
  1597. for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
  1598. }
  1599. else
  1600. {
  1601. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
  1602. int num_used_syms = 0;
  1603. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  1604. for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }
  1605. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  1606. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  1607. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
  1608. MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
  1609. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  1610. for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  1611. }
  1612. next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1613. for (i = 0; i < table_len; i++)
  1614. {
  1615. mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  1616. code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
  1617. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  1618. }
  1619. }
  1620. #define TDEFL_PUT_BITS(b, l) do { \
  1621. mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  1622. d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
  1623. while (d->m_bits_in >= 8) { \
  1624. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  1625. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  1626. d->m_bit_buffer >>= 8; \
  1627. d->m_bits_in -= 8; \
  1628. } \
  1629. } MZ_MACRO_END
  1630. #define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \
  1631. if (rle_repeat_count < 3) { \
  1632. d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  1633. while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  1634. } else { \
  1635. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
  1636. } rle_repeat_count = 0; } }
  1637. #define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \
  1638. if (rle_z_count < 3) { \
  1639. d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  1640. } else if (rle_z_count <= 10) { \
  1641. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
  1642. } else { \
  1643. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
  1644. } rle_z_count = 0; } }
  1645. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  1646. static void tdefl_start_dynamic_block(tdefl_compressor *d)
  1647. {
  1648. int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
  1649. mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
  1650. d->m_huff_count[0][256] = 1;
  1651. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  1652. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  1653. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  1654. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  1655. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  1656. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
  1657. total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
  1658. memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  1659. for (i = 0; i < total_code_sizes_to_pack; i++)
  1660. {
  1661. mz_uint8 code_size = code_sizes_to_pack[i];
  1662. if (!code_size)
  1663. {
  1664. TDEFL_RLE_PREV_CODE_SIZE();
  1665. if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1666. }
  1667. else
  1668. {
  1669. TDEFL_RLE_ZERO_CODE_SIZE();
  1670. if (code_size != prev_code_size)
  1671. {
  1672. TDEFL_RLE_PREV_CODE_SIZE();
  1673. d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size;
  1674. }
  1675. else if (++rle_repeat_count == 6)
  1676. {
  1677. TDEFL_RLE_PREV_CODE_SIZE();
  1678. }
  1679. }
  1680. prev_code_size = code_size;
  1681. }
  1682. if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1683. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  1684. TDEFL_PUT_BITS(2, 2);
  1685. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  1686. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  1687. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;
  1688. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  1689. for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  1690. for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
  1691. {
  1692. mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  1693. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  1694. if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
  1695. }
  1696. }
  1697. static void tdefl_start_static_block(tdefl_compressor *d)
  1698. {
  1699. mz_uint i;
  1700. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  1701. for (i = 0; i <= 143; ++i) *p++ = 8;
  1702. for ( ; i <= 255; ++i) *p++ = 9;
  1703. for ( ; i <= 279; ++i) *p++ = 7;
  1704. for ( ; i <= 287; ++i) *p++ = 8;
  1705. memset(d->m_huff_code_sizes[1], 5, 32);
  1706. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  1707. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  1708. TDEFL_PUT_BITS(1, 2);
  1709. }
  1710. static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  1711. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1712. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1713. {
  1714. mz_uint flags;
  1715. mz_uint8 *pLZ_codes;
  1716. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  1717. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  1718. mz_uint64 bit_buffer = d->m_bit_buffer;
  1719. mz_uint bits_in = d->m_bits_in;
  1720. #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
  1721. flags = 1;
  1722. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)
  1723. {
  1724. if (flags == 1)
  1725. flags = *pLZ_codes++ | 0x100;
  1726. if (flags & 1)
  1727. {
  1728. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  1729. mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3;
  1730. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1731. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1732. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1733. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  1734. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  1735. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  1736. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  1737. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  1738. sym = (match_dist < 512) ? s0 : s1;
  1739. num_extra_bits = (match_dist < 512) ? n0 : n1;
  1740. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1741. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1742. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1743. }
  1744. else
  1745. {
  1746. mz_uint lit = *pLZ_codes++;
  1747. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1748. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1749. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1750. {
  1751. flags >>= 1;
  1752. lit = *pLZ_codes++;
  1753. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1754. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1755. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1756. {
  1757. flags >>= 1;
  1758. lit = *pLZ_codes++;
  1759. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1760. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1761. }
  1762. }
  1763. }
  1764. if (pOutput_buf >= d->m_pOutput_buf_end)
  1765. return MZ_FALSE;
  1766. *(mz_uint64*)pOutput_buf = bit_buffer;
  1767. pOutput_buf += (bits_in >> 3);
  1768. bit_buffer >>= (bits_in & ~7);
  1769. bits_in &= 7;
  1770. }
  1771. #undef TDEFL_PUT_BITS_FAST
  1772. d->m_pOutput_buf = pOutput_buf;
  1773. d->m_bits_in = 0;
  1774. d->m_bit_buffer = 0;
  1775. while (bits_in)
  1776. {
  1777. mz_uint32 n = MZ_MIN(bits_in, 16);
  1778. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  1779. bit_buffer >>= n;
  1780. bits_in -= n;
  1781. }
  1782. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1783. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1784. }
  1785. #else
  1786. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1787. {
  1788. mz_uint flags;
  1789. mz_uint8 *pLZ_codes;
  1790. flags = 1;
  1791. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
  1792. {
  1793. if (flags == 1)
  1794. flags = *pLZ_codes++ | 0x100;
  1795. if (flags & 1)
  1796. {
  1797. mz_uint sym, num_extra_bits;
  1798. mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3;
  1799. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1800. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1801. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1802. if (match_dist < 512)
  1803. {
  1804. sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  1805. }
  1806. else
  1807. {
  1808. sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  1809. }
  1810. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1811. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1812. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1813. }
  1814. else
  1815. {
  1816. mz_uint lit = *pLZ_codes++;
  1817. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1818. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1819. }
  1820. }
  1821. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1822. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1823. }
  1824. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1825. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
  1826. {
  1827. if (static_block)
  1828. tdefl_start_static_block(d);
  1829. else
  1830. tdefl_start_dynamic_block(d);
  1831. return tdefl_compress_lz_codes(d);
  1832. }
  1833. static int tdefl_flush_block(tdefl_compressor *d, int flush)
  1834. {
  1835. mz_uint saved_bit_buf, saved_bits_in;
  1836. mz_uint8 *pSaved_output_buf;
  1837. mz_bool comp_block_succeeded = MZ_FALSE;
  1838. int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  1839. mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;
  1840. d->m_pOutput_buf = pOutput_buf_start;
  1841. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  1842. MZ_ASSERT(!d->m_output_flush_remaining);
  1843. d->m_output_flush_ofs = 0;
  1844. d->m_output_flush_remaining = 0;
  1845. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  1846. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  1847. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
  1848. {
  1849. TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8);
  1850. }
  1851. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  1852. pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
  1853. if (!use_raw_block)
  1854. comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
  1855. // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
  1856. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
  1857. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
  1858. {
  1859. mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1860. TDEFL_PUT_BITS(0, 2);
  1861. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1862. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
  1863. {
  1864. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  1865. }
  1866. for (i = 0; i < d->m_total_lz_bytes; ++i)
  1867. {
  1868. TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
  1869. }
  1870. }
  1871. // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
  1872. else if (!comp_block_succeeded)
  1873. {
  1874. d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1875. tdefl_compress_block(d, MZ_TRUE);
  1876. }
  1877. if (flush)
  1878. {
  1879. if (flush == TDEFL_FINISH)
  1880. {
  1881. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1882. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } }
  1883. }
  1884. else
  1885. {
  1886. mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); }
  1887. }
  1888. }
  1889. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  1890. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  1891. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  1892. d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;
  1893. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
  1894. {
  1895. if (d->m_pPut_buf_func)
  1896. {
  1897. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  1898. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  1899. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  1900. }
  1901. else if (pOutput_buf_start == d->m_output_buf)
  1902. {
  1903. int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  1904. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
  1905. d->m_out_buf_ofs += bytes_to_copy;
  1906. if ((n -= bytes_to_copy) != 0)
  1907. {
  1908. d->m_output_flush_ofs = bytes_to_copy;
  1909. d->m_output_flush_remaining = n;
  1910. }
  1911. }
  1912. else
  1913. {
  1914. d->m_out_buf_ofs += n;
  1915. }
  1916. }
  1917. return d->m_output_flush_remaining;
  1918. }
  1919. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1920. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
  1921. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  1922. {
  1923. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  1924. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  1925. const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q;
  1926. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s);
  1927. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  1928. for ( ; ; )
  1929. {
  1930. for ( ; ; )
  1931. {
  1932. if (--num_probes_left == 0) return;
  1933. #define TDEFL_PROBE \
  1934. next_probe_pos = d->m_next[probe_pos]; \
  1935. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  1936. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  1937. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
  1938. TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  1939. }
  1940. if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32;
  1941. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  1942. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  1943. if (!probe_len)
  1944. {
  1945. *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break;
  1946. }
  1947. else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len)
  1948. {
  1949. *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break;
  1950. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  1951. }
  1952. }
  1953. }
  1954. #else
  1955. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  1956. {
  1957. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  1958. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  1959. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  1960. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  1961. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  1962. for ( ; ; )
  1963. {
  1964. for ( ; ; )
  1965. {
  1966. if (--num_probes_left == 0) return;
  1967. #define TDEFL_PROBE \
  1968. next_probe_pos = d->m_next[probe_pos]; \
  1969. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  1970. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  1971. if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
  1972. TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;
  1973. }
  1974. if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break;
  1975. if (probe_len > match_len)
  1976. {
  1977. *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  1978. c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
  1979. }
  1980. }
  1981. }
  1982. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1983. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  1984. static mz_bool tdefl_compress_fast(tdefl_compressor *d)
  1985. {
  1986. // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
  1987. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;
  1988. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  1989. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  1990. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))
  1991. {
  1992. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  1993. mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  1994. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  1995. d->m_src_buf_left -= num_bytes_to_process;
  1996. lookahead_size += num_bytes_to_process;
  1997. while (num_bytes_to_process)
  1998. {
  1999. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  2000. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  2001. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2002. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  2003. d->m_pSrc += n;
  2004. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  2005. num_bytes_to_process -= n;
  2006. }
  2007. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  2008. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break;
  2009. while (lookahead_size >= 4)
  2010. {
  2011. mz_uint cur_match_dist, cur_match_len = 1;
  2012. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  2013. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  2014. mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;
  2015. mz_uint probe_pos = d->m_hash[hash];
  2016. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  2017. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram))
  2018. {
  2019. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  2020. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  2021. mz_uint32 probe_len = 32;
  2022. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  2023. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  2024. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  2025. if (!probe_len)
  2026. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  2027. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)))
  2028. {
  2029. cur_match_len = 1;
  2030. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2031. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2032. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2033. }
  2034. else
  2035. {
  2036. mz_uint32 s0, s1;
  2037. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  2038. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  2039. cur_match_dist--;
  2040. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  2041. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  2042. pLZ_code_buf += 3;
  2043. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  2044. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  2045. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  2046. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  2047. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
  2048. }
  2049. }
  2050. else
  2051. {
  2052. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2053. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2054. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2055. }
  2056. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2057. total_lz_bytes += cur_match_len;
  2058. lookahead_pos += cur_match_len;
  2059. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  2060. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  2061. MZ_ASSERT(lookahead_size >= cur_match_len);
  2062. lookahead_size -= cur_match_len;
  2063. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2064. {
  2065. int n;
  2066. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2067. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2068. if ((n = tdefl_flush_block(d, 0)) != 0)
  2069. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2070. total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2071. }
  2072. }
  2073. while (lookahead_size)
  2074. {
  2075. mz_uint8 lit = d->m_dict[cur_pos];
  2076. total_lz_bytes++;
  2077. *pLZ_code_buf++ = lit;
  2078. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2079. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2080. d->m_huff_count[0][lit]++;
  2081. lookahead_pos++;
  2082. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  2083. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  2084. lookahead_size--;
  2085. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2086. {
  2087. int n;
  2088. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2089. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2090. if ((n = tdefl_flush_block(d, 0)) != 0)
  2091. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2092. total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2093. }
  2094. }
  2095. }
  2096. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2097. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2098. return MZ_TRUE;
  2099. }
  2100. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2101. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
  2102. {
  2103. d->m_total_lz_bytes++;
  2104. *d->m_pLZ_code_buf++ = lit;
  2105. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2106. d->m_huff_count[0][lit]++;
  2107. }
  2108. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
  2109. {
  2110. mz_uint32 s0, s1;
  2111. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
  2112. d->m_total_lz_bytes += match_len;
  2113. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  2114. match_dist -= 1;
  2115. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  2116. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3;
  2117. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2118. s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  2119. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  2120. if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  2121. }
  2122. static mz_bool tdefl_compress_normal(tdefl_compressor *d)
  2123. {
  2124. const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
  2125. tdefl_flush flush = d->m_flush;
  2126. while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
  2127. {
  2128. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  2129. // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
  2130. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
  2131. {
  2132. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  2133. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2134. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  2135. const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
  2136. src_buf_left -= num_bytes_to_process;
  2137. d->m_lookahead_size += num_bytes_to_process;
  2138. while (pSrc != pSrc_end)
  2139. {
  2140. mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2141. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2142. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2143. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
  2144. }
  2145. }
  2146. else
  2147. {
  2148. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2149. {
  2150. mz_uint8 c = *pSrc++;
  2151. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  2152. src_buf_left--;
  2153. d->m_dict[dst_pos] = c;
  2154. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2155. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2156. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
  2157. {
  2158. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  2159. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2160. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2161. }
  2162. }
  2163. }
  2164. d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  2165. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2166. break;
  2167. // Simple lazy/greedy parsing state machine.
  2168. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  2169. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
  2170. {
  2171. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
  2172. {
  2173. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2174. cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; }
  2175. if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1;
  2176. }
  2177. }
  2178. else
  2179. {
  2180. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  2181. }
  2182. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))
  2183. {
  2184. cur_match_dist = cur_match_len = 0;
  2185. }
  2186. if (d->m_saved_match_len)
  2187. {
  2188. if (cur_match_len > d->m_saved_match_len)
  2189. {
  2190. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  2191. if (cur_match_len >= 128)
  2192. {
  2193. tdefl_record_match(d, cur_match_len, cur_match_dist);
  2194. d->m_saved_match_len = 0; len_to_move = cur_match_len;
  2195. }
  2196. else
  2197. {
  2198. d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2199. }
  2200. }
  2201. else
  2202. {
  2203. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  2204. len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
  2205. }
  2206. }
  2207. else if (!cur_match_dist)
  2208. tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  2209. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
  2210. {
  2211. tdefl_record_match(d, cur_match_len, cur_match_dist);
  2212. len_to_move = cur_match_len;
  2213. }
  2214. else
  2215. {
  2216. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2217. }
  2218. // Move the lookahead forward by len_to_move bytes.
  2219. d->m_lookahead_pos += len_to_move;
  2220. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  2221. d->m_lookahead_size -= len_to_move;
  2222. d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE);
  2223. // Check if it's time to flush the current LZ codes to the internal output buffer.
  2224. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  2225. ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )
  2226. {
  2227. int n;
  2228. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2229. if ((n = tdefl_flush_block(d, 0)) != 0)
  2230. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2231. }
  2232. }
  2233. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2234. return MZ_TRUE;
  2235. }
  2236. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
  2237. {
  2238. if (d->m_pIn_buf_size)
  2239. {
  2240. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  2241. }
  2242. if (d->m_pOut_buf_size)
  2243. {
  2244. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
  2245. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
  2246. d->m_output_flush_ofs += (mz_uint)n;
  2247. d->m_output_flush_remaining -= (mz_uint)n;
  2248. d->m_out_buf_ofs += n;
  2249. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  2250. }
  2251. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
  2252. }
  2253. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)
  2254. {
  2255. if (!d)
  2256. {
  2257. if (pIn_buf_size) *pIn_buf_size = 0;
  2258. if (pOut_buf_size) *pOut_buf_size = 0;
  2259. return TDEFL_STATUS_BAD_PARAM;
  2260. }
  2261. d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
  2262. d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
  2263. d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  2264. d->m_out_buf_ofs = 0;
  2265. d->m_flush = flush;
  2266. if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  2267. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
  2268. {
  2269. if (pIn_buf_size) *pIn_buf_size = 0;
  2270. if (pOut_buf_size) *pOut_buf_size = 0;
  2271. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  2272. }
  2273. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  2274. if ((d->m_output_flush_remaining) || (d->m_finished))
  2275. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2276. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2277. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  2278. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  2279. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))
  2280. {
  2281. if (!tdefl_compress_fast(d))
  2282. return d->m_prev_return_status;
  2283. }
  2284. else
  2285. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2286. {
  2287. if (!tdefl_compress_normal(d))
  2288. return d->m_prev_return_status;
  2289. }
  2290. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
  2291. d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
  2292. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
  2293. {
  2294. if (tdefl_flush_block(d, flush) < 0)
  2295. return d->m_prev_return_status;
  2296. d->m_finished = (flush == TDEFL_FINISH);
  2297. if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; }
  2298. }
  2299. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2300. }
  2301. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
  2302. {
  2303. MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  2304. }
  2305. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2306. {
  2307. d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
  2308. d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  2309. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  2310. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);
  2311. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  2312. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  2313. d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;
  2314. d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;
  2315. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
  2316. d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
  2317. d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
  2318. d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
  2319. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  2320. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  2321. return TDEFL_STATUS_OKAY;
  2322. }
  2323. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
  2324. {
  2325. return d->m_prev_return_status;
  2326. }
  2327. mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
  2328. {
  2329. return d->m_adler32;
  2330. }
  2331. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2332. {
  2333. tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  2334. pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE;
  2335. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
  2336. succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
  2337. MZ_FREE(pComp); return succeeded;
  2338. }
  2339. typedef struct
  2340. {
  2341. size_t m_size, m_capacity;
  2342. mz_uint8 *m_pBuf;
  2343. mz_bool m_expandable;
  2344. } tdefl_output_buffer;
  2345. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
  2346. {
  2347. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  2348. size_t new_size = p->m_size + len;
  2349. if (new_size > p->m_capacity)
  2350. {
  2351. size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE;
  2352. do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity);
  2353. pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE;
  2354. p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
  2355. }
  2356. memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size;
  2357. return MZ_TRUE;
  2358. }
  2359. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  2360. {
  2361. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2362. if (!pOut_len) return MZ_FALSE; else *pOut_len = 0;
  2363. out_buf.m_expandable = MZ_TRUE;
  2364. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL;
  2365. *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
  2366. }
  2367. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  2368. {
  2369. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2370. if (!pOut_buf) return 0;
  2371. out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
  2372. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
  2373. return out_buf.m_size;
  2374. }
  2375. #ifndef MINIZ_NO_ZLIB_APIS
  2376. static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2377. // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
  2378. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
  2379. {
  2380. mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  2381. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  2382. if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  2383. else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
  2384. else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  2385. else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  2386. else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
  2387. return comp_flags;
  2388. }
  2389. #endif //MINIZ_NO_ZLIB_APIS
  2390. #ifdef _MSC_VER
  2391. #pragma warning (push)
  2392. #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
  2393. #endif
  2394. // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
  2395. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  2396. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
  2397. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip)
  2398. {
  2399. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
  2400. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2401. tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0;
  2402. if (!pComp) return NULL;
  2403. MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; }
  2404. // write dummy header
  2405. for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);
  2406. // compress image data
  2407. tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  2408. for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); }
  2409. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2410. // write real header
  2411. *pLen_out = out_buf.m_size-41;
  2412. {
  2413. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  2414. mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
  2415. 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0,
  2416. (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54};
  2417. c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24);
  2418. memcpy(out_buf.m_pBuf, pnghdr, 41);
  2419. }
  2420. // write footer (IDAT CRC-32, followed by IEND chunk)
  2421. if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2422. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24);
  2423. // compute final size of file, grab compressed data buffer and return
  2424. *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf;
  2425. }
  2426. void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out)
  2427. {
  2428. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out)
  2429. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE);
  2430. }
  2431. #ifdef _MSC_VER
  2432. #pragma warning (pop)
  2433. #endif
  2434. // ------------------- .ZIP archive reading
  2435. #ifndef MINIZ_NO_ARCHIVE_APIS
  2436. #ifdef MINIZ_NO_STDIO
  2437. #define MZ_FILE void *
  2438. #else
  2439. #include <stdio.h>
  2440. #include <sys/stat.h>
  2441. #if defined(_MSC_VER) || defined(__MINGW64__)
  2442. static FILE *mz_fopen(const char *pFilename, const char *pMode)
  2443. {
  2444. FILE* pFile = NULL;
  2445. fopen_s(&pFile, pFilename, pMode);
  2446. return pFile;
  2447. }
  2448. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)
  2449. {
  2450. FILE* pFile = NULL;
  2451. if (freopen_s(&pFile, pPath, pMode, pStream))
  2452. return NULL;
  2453. return pFile;
  2454. }
  2455. #ifndef MINIZ_NO_TIME
  2456. #include <sys/utime.h>
  2457. #endif
  2458. #define MZ_FILE FILE
  2459. #define MZ_FOPEN mz_fopen
  2460. #define MZ_FCLOSE fclose
  2461. #define MZ_FREAD fread
  2462. #define MZ_FWRITE fwrite
  2463. #define MZ_FTELL64 _ftelli64
  2464. #define MZ_FSEEK64 _fseeki64
  2465. #define MZ_FILE_STAT_STRUCT _stat
  2466. #define MZ_FILE_STAT _stat
  2467. #define MZ_FFLUSH fflush
  2468. #define MZ_FREOPEN mz_freopen
  2469. #define MZ_DELETE_FILE remove
  2470. #elif defined(__MINGW32__)
  2471. #ifndef MINIZ_NO_TIME
  2472. #include <sys/utime.h>
  2473. #endif
  2474. #define MZ_FILE FILE
  2475. #define MZ_FOPEN(f, m) fopen(f, m)
  2476. #define MZ_FCLOSE fclose
  2477. #define MZ_FREAD fread
  2478. #define MZ_FWRITE fwrite
  2479. #define MZ_FTELL64 ftello64
  2480. #define MZ_FSEEK64 fseeko64
  2481. #define MZ_FILE_STAT_STRUCT _stat
  2482. #define MZ_FILE_STAT _stat
  2483. #define MZ_FFLUSH fflush
  2484. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2485. #define MZ_DELETE_FILE remove
  2486. #elif defined(__TINYC__)
  2487. #ifndef MINIZ_NO_TIME
  2488. #include <sys/utime.h>
  2489. #endif
  2490. #define MZ_FILE FILE
  2491. #define MZ_FOPEN(f, m) fopen(f, m)
  2492. #define MZ_FCLOSE fclose
  2493. #define MZ_FREAD fread
  2494. #define MZ_FWRITE fwrite
  2495. #define MZ_FTELL64 ftell
  2496. #define MZ_FSEEK64 fseek
  2497. #define MZ_FILE_STAT_STRUCT stat
  2498. #define MZ_FILE_STAT stat
  2499. #define MZ_FFLUSH fflush
  2500. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2501. #define MZ_DELETE_FILE remove
  2502. #elif defined(__GNUC__) && _LARGEFILE64_SOURCE
  2503. #ifndef MINIZ_NO_TIME
  2504. #include <utime.h>
  2505. #endif
  2506. #define MZ_FILE FILE
  2507. #define MZ_FOPEN(f, m) fopen64(f, m)
  2508. #define MZ_FCLOSE fclose
  2509. #define MZ_FREAD fread
  2510. #define MZ_FWRITE fwrite
  2511. #define MZ_FTELL64 ftello64
  2512. #define MZ_FSEEK64 fseeko64
  2513. #define MZ_FILE_STAT_STRUCT stat64
  2514. #define MZ_FILE_STAT stat64
  2515. #define MZ_FFLUSH fflush
  2516. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  2517. #define MZ_DELETE_FILE remove
  2518. #else
  2519. #ifndef MINIZ_NO_TIME
  2520. #include <utime.h>
  2521. #endif
  2522. #define MZ_FILE FILE
  2523. #define MZ_FOPEN(f, m) fopen(f, m)
  2524. #define MZ_FCLOSE fclose
  2525. #define MZ_FREAD fread
  2526. #define MZ_FWRITE fwrite
  2527. #define MZ_FTELL64 ftello
  2528. #define MZ_FSEEK64 fseeko
  2529. #define MZ_FILE_STAT_STRUCT stat
  2530. #define MZ_FILE_STAT stat
  2531. #define MZ_FFLUSH fflush
  2532. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2533. #define MZ_DELETE_FILE remove
  2534. #endif // #ifdef _MSC_VER
  2535. #endif // #ifdef MINIZ_NO_STDIO
  2536. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  2537. // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff.
  2538. enum
  2539. {
  2540. // ZIP archive identifiers and record sizes
  2541. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  2542. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  2543. // Central directory header record offsets
  2544. MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  2545. MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16,
  2546. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  2547. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  2548. // Local directory header offsets
  2549. MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  2550. MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  2551. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  2552. // End of central directory offsets
  2553. MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  2554. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  2555. };
  2556. typedef struct
  2557. {
  2558. void *m_p;
  2559. size_t m_size, m_capacity;
  2560. mz_uint m_element_size;
  2561. } mz_zip_array;
  2562. struct mz_zip_internal_state_tag
  2563. {
  2564. mz_zip_array m_central_dir;
  2565. mz_zip_array m_central_dir_offsets;
  2566. mz_zip_array m_sorted_central_dir_offsets;
  2567. MZ_FILE *m_pFile;
  2568. void *m_pMem;
  2569. size_t m_mem_size;
  2570. size_t m_mem_capacity;
  2571. };
  2572. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size
  2573. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]
  2574. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray)
  2575. {
  2576. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  2577. memset(pArray, 0, sizeof(mz_zip_array));
  2578. }
  2579. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing)
  2580. {
  2581. void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  2582. if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; }
  2583. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE;
  2584. pArray->m_p = pNew_p; pArray->m_capacity = new_capacity;
  2585. return MZ_TRUE;
  2586. }
  2587. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing)
  2588. {
  2589. if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; }
  2590. return MZ_TRUE;
  2591. }
  2592. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing)
  2593. {
  2594. if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; }
  2595. pArray->m_size = new_size;
  2596. return MZ_TRUE;
  2597. }
  2598. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n)
  2599. {
  2600. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  2601. }
  2602. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n)
  2603. {
  2604. size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE;
  2605. memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size);
  2606. return MZ_TRUE;
  2607. }
  2608. #ifndef MINIZ_NO_TIME
  2609. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date)
  2610. {
  2611. struct tm tm;
  2612. memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1;
  2613. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31;
  2614. tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62;
  2615. return mktime(&tm);
  2616. }
  2617. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  2618. {
  2619. #ifdef _MSC_VER
  2620. struct tm tm_struct;
  2621. struct tm *tm = &tm_struct;
  2622. errno_t err = localtime_s(tm, &time);
  2623. if (err)
  2624. {
  2625. *pDOS_date = 0; *pDOS_time = 0;
  2626. return;
  2627. }
  2628. #else
  2629. struct tm *tm = localtime(&time);
  2630. #endif
  2631. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1));
  2632. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  2633. }
  2634. #endif
  2635. #ifndef MINIZ_NO_STDIO
  2636. static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  2637. {
  2638. #ifdef MINIZ_NO_TIME
  2639. (void)pFilename; *pDOS_date = *pDOS_time = 0;
  2640. #else
  2641. struct MZ_FILE_STAT_STRUCT file_stat;
  2642. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  2643. if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
  2644. return MZ_FALSE;
  2645. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  2646. #endif // #ifdef MINIZ_NO_TIME
  2647. return MZ_TRUE;
  2648. }
  2649. #ifndef MINIZ_NO_TIME
  2650. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time)
  2651. {
  2652. struct utimbuf t; t.actime = access_time; t.modtime = modified_time;
  2653. return !utime(pFilename, &t);
  2654. }
  2655. #endif // #ifndef MINIZ_NO_TIME
  2656. #endif // #ifndef MINIZ_NO_STDIO
  2657. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags)
  2658. {
  2659. (void)flags;
  2660. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  2661. return MZ_FALSE;
  2662. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  2663. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  2664. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  2665. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  2666. pZip->m_archive_size = 0;
  2667. pZip->m_central_directory_file_ofs = 0;
  2668. pZip->m_total_files = 0;
  2669. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  2670. return MZ_FALSE;
  2671. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  2672. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  2673. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  2674. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  2675. return MZ_TRUE;
  2676. }
  2677. static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index)
  2678. {
  2679. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  2680. const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  2681. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  2682. mz_uint8 l = 0, r = 0;
  2683. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  2684. pE = pL + MZ_MIN(l_len, r_len);
  2685. while (pL < pE)
  2686. {
  2687. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  2688. break;
  2689. pL++; pR++;
  2690. }
  2691. return (pL == pE) ? (l_len < r_len) : (l < r);
  2692. }
  2693. #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END
  2694. // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.)
  2695. static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip)
  2696. {
  2697. mz_zip_internal_state *pState = pZip->m_pState;
  2698. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  2699. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  2700. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  2701. const int size = pZip->m_total_files;
  2702. int start = (size - 2) >> 1, end;
  2703. while (start >= 0)
  2704. {
  2705. int child, root = start;
  2706. for ( ; ; )
  2707. {
  2708. if ((child = (root << 1) + 1) >= size)
  2709. break;
  2710. child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])));
  2711. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  2712. break;
  2713. MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  2714. }
  2715. start--;
  2716. }
  2717. end = size - 1;
  2718. while (end > 0)
  2719. {
  2720. int child, root = 0;
  2721. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  2722. for ( ; ; )
  2723. {
  2724. if ((child = (root << 1) + 1) >= end)
  2725. break;
  2726. child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]));
  2727. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  2728. break;
  2729. MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  2730. }
  2731. end--;
  2732. }
  2733. }
  2734. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags)
  2735. {
  2736. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  2737. mz_uint64 cdir_ofs;
  2738. mz_int64 cur_file_ofs;
  2739. const mz_uint8 *p;
  2740. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  2741. mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  2742. // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there.
  2743. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  2744. return MZ_FALSE;
  2745. // Find the end of central directory record by scanning the file from the end towards the beginning.
  2746. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  2747. for ( ; ; )
  2748. {
  2749. int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  2750. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  2751. return MZ_FALSE;
  2752. for (i = n - 4; i >= 0; --i)
  2753. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
  2754. break;
  2755. if (i >= 0)
  2756. {
  2757. cur_file_ofs += i;
  2758. break;
  2759. }
  2760. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  2761. return MZ_FALSE;
  2762. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  2763. }
  2764. // Read and verify the end of central directory record.
  2765. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  2766. return MZ_FALSE;
  2767. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  2768. ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  2769. return MZ_FALSE;
  2770. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  2771. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  2772. if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1)))
  2773. return MZ_FALSE;
  2774. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  2775. return MZ_FALSE;
  2776. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  2777. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
  2778. return MZ_FALSE;
  2779. pZip->m_central_directory_file_ofs = cdir_ofs;
  2780. if (pZip->m_total_files)
  2781. {
  2782. mz_uint i, n;
  2783. // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices.
  2784. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) ||
  2785. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)))
  2786. return MZ_FALSE;
  2787. if (sort_central_dir)
  2788. {
  2789. if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))
  2790. return MZ_FALSE;
  2791. }
  2792. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size)
  2793. return MZ_FALSE;
  2794. // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported).
  2795. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  2796. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i)
  2797. {
  2798. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  2799. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  2800. return MZ_FALSE;
  2801. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  2802. if (sort_central_dir)
  2803. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i;
  2804. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  2805. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  2806. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF))
  2807. return MZ_FALSE;
  2808. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  2809. if ((disk_index != num_this_disk) && (disk_index != 1))
  2810. return MZ_FALSE;
  2811. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  2812. return MZ_FALSE;
  2813. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n)
  2814. return MZ_FALSE;
  2815. n -= total_header_size; p += total_header_size;
  2816. }
  2817. }
  2818. if (sort_central_dir)
  2819. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  2820. return MZ_TRUE;
  2821. }
  2822. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags)
  2823. {
  2824. if ((!pZip) || (!pZip->m_pRead))
  2825. return MZ_FALSE;
  2826. if (!mz_zip_reader_init_internal(pZip, flags))
  2827. return MZ_FALSE;
  2828. pZip->m_archive_size = size;
  2829. if (!mz_zip_reader_read_central_dir(pZip, flags))
  2830. {
  2831. mz_zip_reader_end(pZip);
  2832. return MZ_FALSE;
  2833. }
  2834. return MZ_TRUE;
  2835. }
  2836. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  2837. {
  2838. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  2839. size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  2840. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  2841. return s;
  2842. }
  2843. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags)
  2844. {
  2845. if (!mz_zip_reader_init_internal(pZip, flags))
  2846. return MZ_FALSE;
  2847. pZip->m_archive_size = size;
  2848. pZip->m_pRead = mz_zip_mem_read_func;
  2849. pZip->m_pIO_opaque = pZip;
  2850. #ifdef __cplusplus
  2851. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  2852. #else
  2853. pZip->m_pState->m_pMem = (void *)pMem;
  2854. #endif
  2855. pZip->m_pState->m_mem_size = size;
  2856. if (!mz_zip_reader_read_central_dir(pZip, flags))
  2857. {
  2858. mz_zip_reader_end(pZip);
  2859. return MZ_FALSE;
  2860. }
  2861. return MZ_TRUE;
  2862. }
  2863. #ifndef MINIZ_NO_STDIO
  2864. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  2865. {
  2866. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  2867. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  2868. if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  2869. return 0;
  2870. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  2871. }
  2872. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags)
  2873. {
  2874. mz_uint64 file_size;
  2875. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  2876. if (!pFile)
  2877. return MZ_FALSE;
  2878. if (MZ_FSEEK64(pFile, 0, SEEK_END))
  2879. {
  2880. MZ_FCLOSE(pFile);
  2881. return MZ_FALSE;
  2882. }
  2883. file_size = MZ_FTELL64(pFile);
  2884. if (!mz_zip_reader_init_internal(pZip, flags))
  2885. {
  2886. MZ_FCLOSE(pFile);
  2887. return MZ_FALSE;
  2888. }
  2889. pZip->m_pRead = mz_zip_file_read_func;
  2890. pZip->m_pIO_opaque = pZip;
  2891. pZip->m_pState->m_pFile = pFile;
  2892. pZip->m_archive_size = file_size;
  2893. if (!mz_zip_reader_read_central_dir(pZip, flags))
  2894. {
  2895. mz_zip_reader_end(pZip);
  2896. return MZ_FALSE;
  2897. }
  2898. return MZ_TRUE;
  2899. }
  2900. #endif // #ifndef MINIZ_NO_STDIO
  2901. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip)
  2902. {
  2903. return pZip ? pZip->m_total_files : 0;
  2904. }
  2905. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index)
  2906. {
  2907. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  2908. return NULL;
  2909. return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  2910. }
  2911. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index)
  2912. {
  2913. mz_uint m_bit_flag;
  2914. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  2915. if (!p)
  2916. return MZ_FALSE;
  2917. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  2918. return (m_bit_flag & 1);
  2919. }
  2920. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index)
  2921. {
  2922. mz_uint filename_len, external_attr;
  2923. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  2924. if (!p)
  2925. return MZ_FALSE;
  2926. // First see if the filename ends with a '/' character.
  2927. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  2928. if (filename_len)
  2929. {
  2930. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  2931. return MZ_TRUE;
  2932. }
  2933. // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct.
  2934. // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field.
  2935. // FIXME: Remove this check? Is it necessary - we already check the filename.
  2936. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  2937. if ((external_attr & 0x10) != 0)
  2938. return MZ_TRUE;
  2939. return MZ_FALSE;
  2940. }
  2941. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat)
  2942. {
  2943. mz_uint n;
  2944. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  2945. if ((!p) || (!pStat))
  2946. return MZ_FALSE;
  2947. // Unpack the central directory record.
  2948. pStat->m_file_index = file_index;
  2949. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  2950. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  2951. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  2952. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  2953. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  2954. #ifndef MINIZ_NO_TIME
  2955. pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  2956. #endif
  2957. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  2958. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  2959. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  2960. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  2961. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  2962. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  2963. // Copy as much of the filename and comment as possible.
  2964. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  2965. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0';
  2966. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  2967. pStat->m_comment_size = n;
  2968. memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0';
  2969. return MZ_TRUE;
  2970. }
  2971. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size)
  2972. {
  2973. mz_uint n;
  2974. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  2975. if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; }
  2976. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  2977. if (filename_buf_size)
  2978. {
  2979. n = MZ_MIN(n, filename_buf_size - 1);
  2980. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  2981. pFilename[n] = '\0';
  2982. }
  2983. return n + 1;
  2984. }
  2985. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags)
  2986. {
  2987. mz_uint i;
  2988. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
  2989. return 0 == memcmp(pA, pB, len);
  2990. for (i = 0; i < len; ++i)
  2991. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
  2992. return MZ_FALSE;
  2993. return MZ_TRUE;
  2994. }
  2995. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len)
  2996. {
  2997. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  2998. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  2999. mz_uint8 l = 0, r = 0;
  3000. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3001. pE = pL + MZ_MIN(l_len, r_len);
  3002. while (pL < pE)
  3003. {
  3004. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  3005. break;
  3006. pL++; pR++;
  3007. }
  3008. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  3009. }
  3010. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename)
  3011. {
  3012. mz_zip_internal_state *pState = pZip->m_pState;
  3013. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  3014. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  3015. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  3016. const int size = pZip->m_total_files;
  3017. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  3018. int l = 0, h = size - 1;
  3019. while (l <= h)
  3020. {
  3021. int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len);
  3022. if (!comp)
  3023. return file_index;
  3024. else if (comp < 0)
  3025. l = m + 1;
  3026. else
  3027. h = m - 1;
  3028. }
  3029. return -1;
  3030. }
  3031. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags)
  3032. {
  3033. mz_uint file_index; size_t name_len, comment_len;
  3034. if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3035. return -1;
  3036. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  3037. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  3038. name_len = strlen(pName); if (name_len > 0xFFFF) return -1;
  3039. comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1;
  3040. for (file_index = 0; file_index < pZip->m_total_files; file_index++)
  3041. {
  3042. const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  3043. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3044. const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3045. if (filename_len < name_len)
  3046. continue;
  3047. if (comment_len)
  3048. {
  3049. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  3050. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  3051. if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags)))
  3052. continue;
  3053. }
  3054. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len))
  3055. {
  3056. int ofs = filename_len - 1;
  3057. do
  3058. {
  3059. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':'))
  3060. break;
  3061. } while (--ofs >= 0);
  3062. ofs++;
  3063. pFilename += ofs; filename_len -= ofs;
  3064. }
  3065. if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  3066. return file_index;
  3067. }
  3068. return -1;
  3069. }
  3070. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3071. {
  3072. int status = TINFL_STATUS_DONE;
  3073. mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  3074. mz_zip_archive_file_stat file_stat;
  3075. void *pRead_buf;
  3076. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3077. tinfl_decompressor inflator;
  3078. if ((buf_size) && (!pBuf))
  3079. return MZ_FALSE;
  3080. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3081. return MZ_FALSE;
  3082. // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3083. if (!file_stat.m_comp_size)
  3084. return MZ_TRUE;
  3085. // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3086. // I'm torn how to handle this case - should it fail instead?
  3087. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3088. return MZ_TRUE;
  3089. // Encryption and patch files are not supported.
  3090. if (file_stat.m_bit_flag & (1 | 32))
  3091. return MZ_FALSE;
  3092. // This function only supports stored and deflate.
  3093. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3094. return MZ_FALSE;
  3095. // Ensure supplied output buffer is large enough.
  3096. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size;
  3097. if (buf_size < needed_size)
  3098. return MZ_FALSE;
  3099. // Read and parse the local directory entry.
  3100. cur_file_ofs = file_stat.m_local_header_ofs;
  3101. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3102. return MZ_FALSE;
  3103. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3104. return MZ_FALSE;
  3105. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3106. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3107. return MZ_FALSE;
  3108. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3109. {
  3110. // The file is stored or the caller has requested the compressed data.
  3111. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size)
  3112. return MZ_FALSE;
  3113. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  3114. }
  3115. // Decompress the file either directly from memory or from a file input buffer.
  3116. tinfl_init(&inflator);
  3117. if (pZip->m_pState->m_pMem)
  3118. {
  3119. // Read directly from the archive in memory.
  3120. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3121. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3122. comp_remaining = 0;
  3123. }
  3124. else if (pUser_read_buf)
  3125. {
  3126. // Use a user provided read buffer.
  3127. if (!user_read_buf_size)
  3128. return MZ_FALSE;
  3129. pRead_buf = (mz_uint8 *)pUser_read_buf;
  3130. read_buf_size = user_read_buf_size;
  3131. read_buf_avail = 0;
  3132. comp_remaining = file_stat.m_comp_size;
  3133. }
  3134. else
  3135. {
  3136. // Temporarily allocate a read buffer.
  3137. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3138. #ifdef _MSC_VER
  3139. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3140. #else
  3141. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3142. #endif
  3143. return MZ_FALSE;
  3144. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3145. return MZ_FALSE;
  3146. read_buf_avail = 0;
  3147. comp_remaining = file_stat.m_comp_size;
  3148. }
  3149. do
  3150. {
  3151. size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  3152. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3153. {
  3154. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3155. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3156. {
  3157. status = TINFL_STATUS_FAILED;
  3158. break;
  3159. }
  3160. cur_file_ofs += read_buf_avail;
  3161. comp_remaining -= read_buf_avail;
  3162. read_buf_ofs = 0;
  3163. }
  3164. in_buf_size = (size_t)read_buf_avail;
  3165. status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  3166. read_buf_avail -= in_buf_size;
  3167. read_buf_ofs += in_buf_size;
  3168. out_buf_ofs += out_buf_size;
  3169. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  3170. if (status == TINFL_STATUS_DONE)
  3171. {
  3172. // Make sure the entire file was decompressed, and check its CRC.
  3173. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  3174. status = TINFL_STATUS_FAILED;
  3175. }
  3176. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  3177. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3178. return status == TINFL_STATUS_DONE;
  3179. }
  3180. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3181. {
  3182. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3183. if (file_index < 0)
  3184. return MZ_FALSE;
  3185. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size);
  3186. }
  3187. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags)
  3188. {
  3189. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0);
  3190. }
  3191. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags)
  3192. {
  3193. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0);
  3194. }
  3195. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags)
  3196. {
  3197. mz_uint64 comp_size, uncomp_size, alloc_size;
  3198. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3199. void *pBuf;
  3200. if (pSize)
  3201. *pSize = 0;
  3202. if (!p)
  3203. return NULL;
  3204. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3205. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3206. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  3207. #ifdef _MSC_VER
  3208. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3209. #else
  3210. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3211. #endif
  3212. return NULL;
  3213. if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  3214. return NULL;
  3215. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags))
  3216. {
  3217. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  3218. return NULL;
  3219. }
  3220. if (pSize) *pSize = (size_t)alloc_size;
  3221. return pBuf;
  3222. }
  3223. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags)
  3224. {
  3225. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3226. if (file_index < 0)
  3227. {
  3228. if (pSize) *pSize = 0;
  3229. return MZ_FALSE;
  3230. }
  3231. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  3232. }
  3233. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3234. {
  3235. int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT;
  3236. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs;
  3237. mz_zip_archive_file_stat file_stat;
  3238. void *pRead_buf = NULL; void *pWrite_buf = NULL;
  3239. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3240. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3241. return MZ_FALSE;
  3242. // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3243. if (!file_stat.m_comp_size)
  3244. return MZ_TRUE;
  3245. // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3246. // I'm torn how to handle this case - should it fail instead?
  3247. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3248. return MZ_TRUE;
  3249. // Encryption and patch files are not supported.
  3250. if (file_stat.m_bit_flag & (1 | 32))
  3251. return MZ_FALSE;
  3252. // This function only supports stored and deflate.
  3253. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3254. return MZ_FALSE;
  3255. // Read and parse the local directory entry.
  3256. cur_file_ofs = file_stat.m_local_header_ofs;
  3257. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3258. return MZ_FALSE;
  3259. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3260. return MZ_FALSE;
  3261. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3262. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3263. return MZ_FALSE;
  3264. // Decompress the file either directly from memory or from a file input buffer.
  3265. if (pZip->m_pState->m_pMem)
  3266. {
  3267. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3268. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3269. comp_remaining = 0;
  3270. }
  3271. else
  3272. {
  3273. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3274. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3275. return MZ_FALSE;
  3276. read_buf_avail = 0;
  3277. comp_remaining = file_stat.m_comp_size;
  3278. }
  3279. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3280. {
  3281. // The file is stored or the caller has requested the compressed data.
  3282. if (pZip->m_pState->m_pMem)
  3283. {
  3284. #ifdef _MSC_VER
  3285. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3286. #else
  3287. if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3288. #endif
  3289. return MZ_FALSE;
  3290. if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  3291. status = TINFL_STATUS_FAILED;
  3292. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3293. file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size);
  3294. cur_file_ofs += file_stat.m_comp_size;
  3295. out_buf_ofs += file_stat.m_comp_size;
  3296. comp_remaining = 0;
  3297. }
  3298. else
  3299. {
  3300. while (comp_remaining)
  3301. {
  3302. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3303. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3304. {
  3305. status = TINFL_STATUS_FAILED;
  3306. break;
  3307. }
  3308. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3309. file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  3310. if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3311. {
  3312. status = TINFL_STATUS_FAILED;
  3313. break;
  3314. }
  3315. cur_file_ofs += read_buf_avail;
  3316. out_buf_ofs += read_buf_avail;
  3317. comp_remaining -= read_buf_avail;
  3318. }
  3319. }
  3320. }
  3321. else
  3322. {
  3323. tinfl_decompressor inflator;
  3324. tinfl_init(&inflator);
  3325. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))
  3326. status = TINFL_STATUS_FAILED;
  3327. else
  3328. {
  3329. do
  3330. {
  3331. mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3332. size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3333. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3334. {
  3335. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3336. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3337. {
  3338. status = TINFL_STATUS_FAILED;
  3339. break;
  3340. }
  3341. cur_file_ofs += read_buf_avail;
  3342. comp_remaining -= read_buf_avail;
  3343. read_buf_ofs = 0;
  3344. }
  3345. in_buf_size = (size_t)read_buf_avail;
  3346. status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  3347. read_buf_avail -= in_buf_size;
  3348. read_buf_ofs += in_buf_size;
  3349. if (out_buf_size)
  3350. {
  3351. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size)
  3352. {
  3353. status = TINFL_STATUS_FAILED;
  3354. break;
  3355. }
  3356. file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  3357. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size)
  3358. {
  3359. status = TINFL_STATUS_FAILED;
  3360. break;
  3361. }
  3362. }
  3363. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  3364. }
  3365. }
  3366. if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))
  3367. {
  3368. // Make sure the entire file was decompressed, and check its CRC.
  3369. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32))
  3370. status = TINFL_STATUS_FAILED;
  3371. }
  3372. if (!pZip->m_pState->m_pMem)
  3373. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3374. if (pWrite_buf)
  3375. pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  3376. return status == TINFL_STATUS_DONE;
  3377. }
  3378. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3379. {
  3380. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3381. if (file_index < 0)
  3382. return MZ_FALSE;
  3383. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags);
  3384. }
  3385. #ifndef MINIZ_NO_STDIO
  3386. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)
  3387. {
  3388. (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque);
  3389. }
  3390. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags)
  3391. {
  3392. mz_bool status;
  3393. mz_zip_archive_file_stat file_stat;
  3394. MZ_FILE *pFile;
  3395. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3396. return MZ_FALSE;
  3397. pFile = MZ_FOPEN(pDst_filename, "wb");
  3398. if (!pFile)
  3399. return MZ_FALSE;
  3400. status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  3401. if (MZ_FCLOSE(pFile) == EOF)
  3402. return MZ_FALSE;
  3403. #ifndef MINIZ_NO_TIME
  3404. if (status)
  3405. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  3406. #endif
  3407. return status;
  3408. }
  3409. #endif // #ifndef MINIZ_NO_STDIO
  3410. mz_bool mz_zip_reader_end(mz_zip_archive *pZip)
  3411. {
  3412. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3413. return MZ_FALSE;
  3414. if (pZip->m_pState)
  3415. {
  3416. mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL;
  3417. mz_zip_array_clear(pZip, &pState->m_central_dir);
  3418. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  3419. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  3420. #ifndef MINIZ_NO_STDIO
  3421. if (pState->m_pFile)
  3422. {
  3423. MZ_FCLOSE(pState->m_pFile);
  3424. pState->m_pFile = NULL;
  3425. }
  3426. #endif // #ifndef MINIZ_NO_STDIO
  3427. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  3428. }
  3429. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  3430. return MZ_TRUE;
  3431. }
  3432. #ifndef MINIZ_NO_STDIO
  3433. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags)
  3434. {
  3435. int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  3436. if (file_index < 0)
  3437. return MZ_FALSE;
  3438. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  3439. }
  3440. #endif
  3441. // ------------------- .ZIP archive writing
  3442. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  3443. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); }
  3444. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); }
  3445. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  3446. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  3447. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size)
  3448. {
  3449. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  3450. return MZ_FALSE;
  3451. if (pZip->m_file_offset_alignment)
  3452. {
  3453. // Ensure user specified file offset alignment is a power of 2.
  3454. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  3455. return MZ_FALSE;
  3456. }
  3457. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  3458. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  3459. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  3460. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  3461. pZip->m_archive_size = existing_size;
  3462. pZip->m_central_directory_file_ofs = 0;
  3463. pZip->m_total_files = 0;
  3464. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  3465. return MZ_FALSE;
  3466. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  3467. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  3468. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  3469. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  3470. return MZ_TRUE;
  3471. }
  3472. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  3473. {
  3474. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3475. mz_zip_internal_state *pState = pZip->m_pState;
  3476. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  3477. #ifdef _MSC_VER
  3478. if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  3479. #else
  3480. if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  3481. #endif
  3482. return 0;
  3483. if (new_size > pState->m_mem_capacity)
  3484. {
  3485. void *pNew_block;
  3486. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2;
  3487. if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  3488. return 0;
  3489. pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity;
  3490. }
  3491. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  3492. pState->m_mem_size = (size_t)new_size;
  3493. return n;
  3494. }
  3495. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size)
  3496. {
  3497. pZip->m_pWrite = mz_zip_heap_write_func;
  3498. pZip->m_pIO_opaque = pZip;
  3499. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  3500. return MZ_FALSE;
  3501. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning)))
  3502. {
  3503. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size)))
  3504. {
  3505. mz_zip_writer_end(pZip);
  3506. return MZ_FALSE;
  3507. }
  3508. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  3509. }
  3510. return MZ_TRUE;
  3511. }
  3512. #ifndef MINIZ_NO_STDIO
  3513. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  3514. {
  3515. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3516. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  3517. if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  3518. return 0;
  3519. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  3520. }
  3521. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning)
  3522. {
  3523. MZ_FILE *pFile;
  3524. pZip->m_pWrite = mz_zip_file_write_func;
  3525. pZip->m_pIO_opaque = pZip;
  3526. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  3527. return MZ_FALSE;
  3528. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb")))
  3529. {
  3530. mz_zip_writer_end(pZip);
  3531. return MZ_FALSE;
  3532. }
  3533. pZip->m_pState->m_pFile = pFile;
  3534. if (size_to_reserve_at_beginning)
  3535. {
  3536. mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf);
  3537. do
  3538. {
  3539. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  3540. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n)
  3541. {
  3542. mz_zip_writer_end(pZip);
  3543. return MZ_FALSE;
  3544. }
  3545. cur_ofs += n; size_to_reserve_at_beginning -= n;
  3546. } while (size_to_reserve_at_beginning);
  3547. }
  3548. return MZ_TRUE;
  3549. }
  3550. #endif // #ifndef MINIZ_NO_STDIO
  3551. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename)
  3552. {
  3553. mz_zip_internal_state *pState;
  3554. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3555. return MZ_FALSE;
  3556. // No sense in trying to write to an archive that's already at the support max size
  3557. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  3558. return MZ_FALSE;
  3559. pState = pZip->m_pState;
  3560. if (pState->m_pFile)
  3561. {
  3562. #ifdef MINIZ_NO_STDIO
  3563. pFilename; return MZ_FALSE;
  3564. #else
  3565. // Archive is being read from stdio - try to reopen as writable.
  3566. if (pZip->m_pIO_opaque != pZip)
  3567. return MZ_FALSE;
  3568. if (!pFilename)
  3569. return MZ_FALSE;
  3570. pZip->m_pWrite = mz_zip_file_write_func;
  3571. if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile)))
  3572. {
  3573. // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it.
  3574. mz_zip_reader_end(pZip);
  3575. return MZ_FALSE;
  3576. }
  3577. #endif // #ifdef MINIZ_NO_STDIO
  3578. }
  3579. else if (pState->m_pMem)
  3580. {
  3581. // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback.
  3582. if (pZip->m_pIO_opaque != pZip)
  3583. return MZ_FALSE;
  3584. pState->m_mem_capacity = pState->m_mem_size;
  3585. pZip->m_pWrite = mz_zip_heap_write_func;
  3586. }
  3587. // Archive is being read via a user provided read function - make sure the user has specified a write function too.
  3588. else if (!pZip->m_pWrite)
  3589. return MZ_FALSE;
  3590. // Start writing new files at the archive's current central directory location.
  3591. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  3592. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  3593. pZip->m_central_directory_file_ofs = 0;
  3594. return MZ_TRUE;
  3595. }
  3596. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags)
  3597. {
  3598. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0);
  3599. }
  3600. typedef struct
  3601. {
  3602. mz_zip_archive *m_pZip;
  3603. mz_uint64 m_cur_archive_file_ofs;
  3604. mz_uint64 m_comp_size;
  3605. } mz_zip_writer_add_state;
  3606. static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser)
  3607. {
  3608. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  3609. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len)
  3610. return MZ_FALSE;
  3611. pState->m_cur_archive_file_ofs += len;
  3612. pState->m_comp_size += len;
  3613. return MZ_TRUE;
  3614. }
  3615. static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date)
  3616. {
  3617. (void)pZip;
  3618. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  3619. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  3620. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  3621. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  3622. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  3623. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  3624. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  3625. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  3626. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  3627. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  3628. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  3629. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  3630. return MZ_TRUE;
  3631. }
  3632. static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  3633. {
  3634. (void)pZip;
  3635. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  3636. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  3637. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  3638. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  3639. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  3640. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  3641. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  3642. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  3643. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  3644. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  3645. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  3646. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  3647. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  3648. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  3649. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  3650. return MZ_TRUE;
  3651. }
  3652. static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  3653. {
  3654. mz_zip_internal_state *pState = pZip->m_pState;
  3655. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  3656. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  3657. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  3658. // No zip64 support yet
  3659. if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF))
  3660. return MZ_FALSE;
  3661. if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes))
  3662. return MZ_FALSE;
  3663. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  3664. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) ||
  3665. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) ||
  3666. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) ||
  3667. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1)))
  3668. {
  3669. // Try to push the central directory array back into its original state.
  3670. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  3671. return MZ_FALSE;
  3672. }
  3673. return MZ_TRUE;
  3674. }
  3675. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name)
  3676. {
  3677. // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes.
  3678. if (*pArchive_name == '/')
  3679. return MZ_FALSE;
  3680. while (*pArchive_name)
  3681. {
  3682. if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
  3683. return MZ_FALSE;
  3684. pArchive_name++;
  3685. }
  3686. return MZ_TRUE;
  3687. }
  3688. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip)
  3689. {
  3690. mz_uint32 n;
  3691. if (!pZip->m_file_offset_alignment)
  3692. return 0;
  3693. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  3694. return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1);
  3695. }
  3696. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n)
  3697. {
  3698. char buf[4096];
  3699. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  3700. while (n)
  3701. {
  3702. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  3703. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  3704. return MZ_FALSE;
  3705. cur_file_ofs += s; n -= s;
  3706. }
  3707. return MZ_TRUE;
  3708. }
  3709. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32)
  3710. {
  3711. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  3712. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  3713. mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  3714. size_t archive_name_size;
  3715. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  3716. tdefl_compressor *pComp = NULL;
  3717. mz_bool store_data_uncompressed;
  3718. mz_zip_internal_state *pState;
  3719. if ((int)level_and_flags < 0)
  3720. level_and_flags = MZ_DEFAULT_LEVEL;
  3721. level = level_and_flags & 0xF;
  3722. store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  3723. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  3724. return MZ_FALSE;
  3725. pState = pZip->m_pState;
  3726. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  3727. return MZ_FALSE;
  3728. // No zip64 support yet
  3729. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
  3730. return MZ_FALSE;
  3731. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  3732. return MZ_FALSE;
  3733. #ifndef MINIZ_NO_TIME
  3734. {
  3735. time_t cur_time; time(&cur_time);
  3736. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  3737. }
  3738. #endif // #ifndef MINIZ_NO_TIME
  3739. archive_name_size = strlen(pArchive_name);
  3740. if (archive_name_size > 0xFFFF)
  3741. return MZ_FALSE;
  3742. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  3743. // no zip64 support yet
  3744. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  3745. return MZ_FALSE;
  3746. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/'))
  3747. {
  3748. // Set DOS Subdirectory attribute bit.
  3749. ext_attributes |= 0x10;
  3750. // Subdirectories cannot contain data.
  3751. if ((buf_size) || (uncomp_size))
  3752. return MZ_FALSE;
  3753. }
  3754. // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.)
  3755. if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  3756. return MZ_FALSE;
  3757. if ((!store_data_uncompressed) && (buf_size))
  3758. {
  3759. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  3760. return MZ_FALSE;
  3761. }
  3762. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  3763. {
  3764. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3765. return MZ_FALSE;
  3766. }
  3767. local_dir_header_ofs += num_alignment_padding_bytes;
  3768. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  3769. cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  3770. MZ_CLEAR_OBJ(local_dir_header);
  3771. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  3772. {
  3773. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3774. return MZ_FALSE;
  3775. }
  3776. cur_archive_file_ofs += archive_name_size;
  3777. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3778. {
  3779. uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size);
  3780. uncomp_size = buf_size;
  3781. if (uncomp_size <= 3)
  3782. {
  3783. level = 0;
  3784. store_data_uncompressed = MZ_TRUE;
  3785. }
  3786. }
  3787. if (store_data_uncompressed)
  3788. {
  3789. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size)
  3790. {
  3791. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3792. return MZ_FALSE;
  3793. }
  3794. cur_archive_file_ofs += buf_size;
  3795. comp_size = buf_size;
  3796. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  3797. method = MZ_DEFLATED;
  3798. }
  3799. else if (buf_size)
  3800. {
  3801. mz_zip_writer_add_state state;
  3802. state.m_pZip = pZip;
  3803. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  3804. state.m_comp_size = 0;
  3805. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) ||
  3806. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE))
  3807. {
  3808. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3809. return MZ_FALSE;
  3810. }
  3811. comp_size = state.m_comp_size;
  3812. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  3813. method = MZ_DEFLATED;
  3814. }
  3815. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3816. pComp = NULL;
  3817. // no zip64 support yet
  3818. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  3819. return MZ_FALSE;
  3820. if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  3821. return MZ_FALSE;
  3822. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  3823. return MZ_FALSE;
  3824. if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  3825. return MZ_FALSE;
  3826. pZip->m_total_files++;
  3827. pZip->m_archive_size = cur_archive_file_ofs;
  3828. return MZ_TRUE;
  3829. }
  3830. #ifndef MINIZ_NO_STDIO
  3831. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  3832. {
  3833. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  3834. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  3835. mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0;
  3836. size_t archive_name_size;
  3837. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  3838. MZ_FILE *pSrc_file = NULL;
  3839. if ((int)level_and_flags < 0)
  3840. level_and_flags = MZ_DEFAULT_LEVEL;
  3841. level = level_and_flags & 0xF;
  3842. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  3843. return MZ_FALSE;
  3844. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  3845. return MZ_FALSE;
  3846. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  3847. return MZ_FALSE;
  3848. archive_name_size = strlen(pArchive_name);
  3849. if (archive_name_size > 0xFFFF)
  3850. return MZ_FALSE;
  3851. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  3852. // no zip64 support yet
  3853. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  3854. return MZ_FALSE;
  3855. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  3856. return MZ_FALSE;
  3857. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  3858. if (!pSrc_file)
  3859. return MZ_FALSE;
  3860. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  3861. uncomp_size = MZ_FTELL64(pSrc_file);
  3862. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  3863. if (uncomp_size > 0xFFFFFFFF)
  3864. {
  3865. // No zip64 support yet
  3866. MZ_FCLOSE(pSrc_file);
  3867. return MZ_FALSE;
  3868. }
  3869. if (uncomp_size <= 3)
  3870. level = 0;
  3871. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  3872. {
  3873. MZ_FCLOSE(pSrc_file);
  3874. return MZ_FALSE;
  3875. }
  3876. local_dir_header_ofs += num_alignment_padding_bytes;
  3877. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  3878. cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  3879. MZ_CLEAR_OBJ(local_dir_header);
  3880. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  3881. {
  3882. MZ_FCLOSE(pSrc_file);
  3883. return MZ_FALSE;
  3884. }
  3885. cur_archive_file_ofs += archive_name_size;
  3886. if (uncomp_size)
  3887. {
  3888. mz_uint64 uncomp_remaining = uncomp_size;
  3889. void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  3890. if (!pRead_buf)
  3891. {
  3892. MZ_FCLOSE(pSrc_file);
  3893. return MZ_FALSE;
  3894. }
  3895. if (!level)
  3896. {
  3897. while (uncomp_remaining)
  3898. {
  3899. mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  3900. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n))
  3901. {
  3902. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3903. MZ_FCLOSE(pSrc_file);
  3904. return MZ_FALSE;
  3905. }
  3906. uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  3907. uncomp_remaining -= n;
  3908. cur_archive_file_ofs += n;
  3909. }
  3910. comp_size = uncomp_size;
  3911. }
  3912. else
  3913. {
  3914. mz_bool result = MZ_FALSE;
  3915. mz_zip_writer_add_state state;
  3916. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  3917. if (!pComp)
  3918. {
  3919. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3920. MZ_FCLOSE(pSrc_file);
  3921. return MZ_FALSE;
  3922. }
  3923. state.m_pZip = pZip;
  3924. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  3925. state.m_comp_size = 0;
  3926. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY)
  3927. {
  3928. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3929. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3930. MZ_FCLOSE(pSrc_file);
  3931. return MZ_FALSE;
  3932. }
  3933. for ( ; ; )
  3934. {
  3935. size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE);
  3936. tdefl_status status;
  3937. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  3938. break;
  3939. uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  3940. uncomp_remaining -= in_buf_size;
  3941. status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  3942. if (status == TDEFL_STATUS_DONE)
  3943. {
  3944. result = MZ_TRUE;
  3945. break;
  3946. }
  3947. else if (status != TDEFL_STATUS_OKAY)
  3948. break;
  3949. }
  3950. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3951. if (!result)
  3952. {
  3953. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3954. MZ_FCLOSE(pSrc_file);
  3955. return MZ_FALSE;
  3956. }
  3957. comp_size = state.m_comp_size;
  3958. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  3959. method = MZ_DEFLATED;
  3960. }
  3961. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3962. }
  3963. MZ_FCLOSE(pSrc_file); pSrc_file = NULL;
  3964. // no zip64 support yet
  3965. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  3966. return MZ_FALSE;
  3967. if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  3968. return MZ_FALSE;
  3969. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  3970. return MZ_FALSE;
  3971. if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  3972. return MZ_FALSE;
  3973. pZip->m_total_files++;
  3974. pZip->m_archive_size = cur_archive_file_ofs;
  3975. return MZ_TRUE;
  3976. }
  3977. #endif // #ifndef MINIZ_NO_STDIO
  3978. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index)
  3979. {
  3980. mz_uint n, bit_flags, num_alignment_padding_bytes;
  3981. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  3982. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  3983. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3984. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  3985. size_t orig_central_dir_size;
  3986. mz_zip_internal_state *pState;
  3987. void *pBuf; const mz_uint8 *pSrc_central_header;
  3988. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  3989. return MZ_FALSE;
  3990. if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  3991. return MZ_FALSE;
  3992. pState = pZip->m_pState;
  3993. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  3994. // no zip64 support yet
  3995. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  3996. return MZ_FALSE;
  3997. cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  3998. cur_dst_file_ofs = pZip->m_archive_size;
  3999. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4000. return MZ_FALSE;
  4001. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4002. return MZ_FALSE;
  4003. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4004. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes))
  4005. return MZ_FALSE;
  4006. cur_dst_file_ofs += num_alignment_padding_bytes;
  4007. local_dir_header_ofs = cur_dst_file_ofs;
  4008. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4009. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4010. return MZ_FALSE;
  4011. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4012. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4013. comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4014. if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining)))))
  4015. return MZ_FALSE;
  4016. while (comp_bytes_remaining)
  4017. {
  4018. n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  4019. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n)
  4020. {
  4021. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4022. return MZ_FALSE;
  4023. }
  4024. cur_src_file_ofs += n;
  4025. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4026. {
  4027. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4028. return MZ_FALSE;
  4029. }
  4030. cur_dst_file_ofs += n;
  4031. comp_bytes_remaining -= n;
  4032. }
  4033. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  4034. if (bit_flags & 8)
  4035. {
  4036. // Copy data descriptor
  4037. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4)
  4038. {
  4039. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4040. return MZ_FALSE;
  4041. }
  4042. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  4043. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4044. {
  4045. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4046. return MZ_FALSE;
  4047. }
  4048. cur_src_file_ofs += n;
  4049. cur_dst_file_ofs += n;
  4050. }
  4051. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4052. // no zip64 support yet
  4053. if (cur_dst_file_ofs > 0xFFFFFFFF)
  4054. return MZ_FALSE;
  4055. orig_central_dir_size = pState->m_central_dir.m_size;
  4056. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  4057. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs);
  4058. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  4059. return MZ_FALSE;
  4060. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4061. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n))
  4062. {
  4063. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4064. return MZ_FALSE;
  4065. }
  4066. if (pState->m_central_dir.m_size > 0xFFFFFFFF)
  4067. return MZ_FALSE;
  4068. n = (mz_uint32)orig_central_dir_size;
  4069. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1))
  4070. {
  4071. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4072. return MZ_FALSE;
  4073. }
  4074. pZip->m_total_files++;
  4075. pZip->m_archive_size = cur_dst_file_ofs;
  4076. return MZ_TRUE;
  4077. }
  4078. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip)
  4079. {
  4080. mz_zip_internal_state *pState;
  4081. mz_uint64 central_dir_ofs, central_dir_size;
  4082. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  4083. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  4084. return MZ_FALSE;
  4085. pState = pZip->m_pState;
  4086. // no zip64 support yet
  4087. if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4088. return MZ_FALSE;
  4089. central_dir_ofs = 0;
  4090. central_dir_size = 0;
  4091. if (pZip->m_total_files)
  4092. {
  4093. // Write central directory
  4094. central_dir_ofs = pZip->m_archive_size;
  4095. central_dir_size = pState->m_central_dir.m_size;
  4096. pZip->m_central_directory_file_ofs = central_dir_ofs;
  4097. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size)
  4098. return MZ_FALSE;
  4099. pZip->m_archive_size += central_dir_size;
  4100. }
  4101. // Write end of central directory record
  4102. MZ_CLEAR_OBJ(hdr);
  4103. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  4104. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files);
  4105. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  4106. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  4107. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  4108. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr))
  4109. return MZ_FALSE;
  4110. #ifndef MINIZ_NO_STDIO
  4111. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
  4112. return MZ_FALSE;
  4113. #endif // #ifndef MINIZ_NO_STDIO
  4114. pZip->m_archive_size += sizeof(hdr);
  4115. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  4116. return MZ_TRUE;
  4117. }
  4118. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize)
  4119. {
  4120. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
  4121. return MZ_FALSE;
  4122. if (pZip->m_pWrite != mz_zip_heap_write_func)
  4123. return MZ_FALSE;
  4124. if (!mz_zip_writer_finalize_archive(pZip))
  4125. return MZ_FALSE;
  4126. *pBuf = pZip->m_pState->m_pMem;
  4127. *pSize = pZip->m_pState->m_mem_size;
  4128. pZip->m_pState->m_pMem = NULL;
  4129. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  4130. return MZ_TRUE;
  4131. }
  4132. mz_bool mz_zip_writer_end(mz_zip_archive *pZip)
  4133. {
  4134. mz_zip_internal_state *pState;
  4135. mz_bool status = MZ_TRUE;
  4136. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  4137. return MZ_FALSE;
  4138. pState = pZip->m_pState;
  4139. pZip->m_pState = NULL;
  4140. mz_zip_array_clear(pZip, &pState->m_central_dir);
  4141. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  4142. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  4143. #ifndef MINIZ_NO_STDIO
  4144. if (pState->m_pFile)
  4145. {
  4146. MZ_FCLOSE(pState->m_pFile);
  4147. pState->m_pFile = NULL;
  4148. }
  4149. #endif // #ifndef MINIZ_NO_STDIO
  4150. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem))
  4151. {
  4152. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  4153. pState->m_pMem = NULL;
  4154. }
  4155. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  4156. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  4157. return status;
  4158. }
  4159. #ifndef MINIZ_NO_STDIO
  4160. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  4161. {
  4162. mz_bool status, created_new_archive = MZ_FALSE;
  4163. mz_zip_archive zip_archive;
  4164. struct MZ_FILE_STAT_STRUCT file_stat;
  4165. MZ_CLEAR_OBJ(zip_archive);
  4166. if ((int)level_and_flags < 0)
  4167. level_and_flags = MZ_DEFAULT_LEVEL;
  4168. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  4169. return MZ_FALSE;
  4170. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4171. return MZ_FALSE;
  4172. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0)
  4173. {
  4174. // Create a new archive.
  4175. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  4176. return MZ_FALSE;
  4177. created_new_archive = MZ_TRUE;
  4178. }
  4179. else
  4180. {
  4181. // Append to an existing archive.
  4182. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4183. return MZ_FALSE;
  4184. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename))
  4185. {
  4186. mz_zip_reader_end(&zip_archive);
  4187. return MZ_FALSE;
  4188. }
  4189. }
  4190. status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0);
  4191. // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.)
  4192. if (!mz_zip_writer_finalize_archive(&zip_archive))
  4193. status = MZ_FALSE;
  4194. if (!mz_zip_writer_end(&zip_archive))
  4195. status = MZ_FALSE;
  4196. if ((!status) && (created_new_archive))
  4197. {
  4198. // It's a new archive and something went wrong, so just delete it.
  4199. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  4200. (void)ignoredStatus;
  4201. }
  4202. return status;
  4203. }
  4204. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags)
  4205. {
  4206. int file_index;
  4207. mz_zip_archive zip_archive;
  4208. void *p = NULL;
  4209. if (pSize)
  4210. *pSize = 0;
  4211. if ((!pZip_filename) || (!pArchive_name))
  4212. return NULL;
  4213. MZ_CLEAR_OBJ(zip_archive);
  4214. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4215. return NULL;
  4216. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0)
  4217. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  4218. mz_zip_reader_end(&zip_archive);
  4219. return p;
  4220. }
  4221. #endif // #ifndef MINIZ_NO_STDIO
  4222. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  4223. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  4224. #ifdef __cplusplus
  4225. }
  4226. #endif
  4227. #endif // MINIZ_HEADER_FILE_ONLY
  4228. /*
  4229. This is free and unencumbered software released into the public domain.
  4230. Anyone is free to copy, modify, publish, use, compile, sell, or
  4231. distribute this software, either in source code form or as a compiled
  4232. binary, for any purpose, commercial or non-commercial, and by any
  4233. means.
  4234. In jurisdictions that recognize copyright laws, the author or authors
  4235. of this software dedicate any and all copyright interest in the
  4236. software to the public domain. We make this dedication for the benefit
  4237. of the public at large and to the detriment of our heirs and
  4238. successors. We intend this dedication to be an overt act of
  4239. relinquishment in perpetuity of all present and future rights to this
  4240. software under copyright law.
  4241. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  4242. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4243. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  4244. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  4245. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  4246. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  4247. OTHER DEALINGS IN THE SOFTWARE.
  4248. For more information, please refer to <http://unlicense.org/>
  4249. */