wm_tool.c 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <ctype.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <getopt.h>
  9. #include <dirent.h>
  10. #include <unistd.h>
  11. #include <stdarg.h>
  12. #ifdef __MINGW32__
  13. #include <windows.h>
  14. #else
  15. #include <signal.h>
  16. #include <pthread.h>
  17. #include <termios.h>
  18. #include <sys/ioctl.h>
  19. #endif
  20. #define WM_TOOL_PATH_MAX 256
  21. #define WM_TOOL_ONCE_READ_LEN 1024
  22. #define WM_TOOL_RUN_IMG_HEADER_LEN 0x100
  23. #define WM_TOOL_SECBOOT_IMG_ADDR (0x2100)
  24. #define WM_TOOL_SECBOOT_HEADER_LEN (0x100)
  25. #define WM_TOOL_SECBOOT_HEADER_POS (WM_TOOL_SECBOOT_IMG_ADDR - WM_TOOL_SECBOOT_HEADER_LEN)
  26. //#define WM_TOOL_SECBOOT_IMG_AREA_TOTAL_LEN 9216//(56 * 1024)
  27. #define WM_TOOL_IMG_HEAD_MAGIC_NO (0xA0FFFF9F)
  28. #define WM_TOOL_DEFAULT_BAUD_RATE 115200
  29. #define WM_TOOL_DOWNLOAD_TIMEOUT_SEC (60 * 1)
  30. #define WM_TOOL_USE_1K_XMODEM 1 /* 1 for use 1k_xmodem 0 for xmodem */
  31. #define WM_TOOL_IMAGE_VERSION_LEN 16
  32. /* Xmodem Frame form: <SOH><blk #><255-blk #><--128 data bytes--><CRC hi><CRC lo> */
  33. #define XMODEM_SOH 0x01
  34. #define XMODEM_STX 0x02
  35. #define XMODEM_EOT 0x04
  36. #define XMODEM_ACK 0x06
  37. #define XMODEM_NAK 0x15
  38. #define XMODEM_CAN 0x18
  39. #define XMODEM_CRC_CHR 'C'
  40. #define XMODEM_CRC_SIZE 2 /* Crc_High Byte + Crc_Low Byte */
  41. #define XMODEM_FRAME_ID_SIZE 2 /* Frame_Id + 255-Frame_Id */
  42. #define XMODEM_DATA_SIZE_SOH 128 /* for Xmodem protocol */
  43. #define XMODEM_DATA_SIZE_STX 1024 /* for 1K xmodem protocol */
  44. #if (WM_TOOL_USE_1K_XMODEM)
  45. #define XMODEM_DATA_SIZE XMODEM_DATA_SIZE_STX
  46. #define XMODEM_HEAD XMODEM_STX
  47. #else
  48. #define XMODEM_DATA_SIZE XMODEM_DATA_SIZE_SOH
  49. #define XMODEM_HEAD XMODEM_SOH
  50. #endif
  51. #ifdef WM_DEBUG
  52. #define WM_TOOL_DBG_PRINT wm_tool_printf
  53. #else
  54. #define WM_TOOL_DBG_PRINT(...)
  55. #endif
  56. typedef enum {
  57. WM_TOOL_DL_ACTION_NONE = 0,
  58. WM_TOOL_DL_ACTION_AT,
  59. WM_TOOL_DL_ACTION_RTS
  60. } wm_tool_dl_action_e;
  61. typedef enum {
  62. WM_TOOL_DL_ERASE_NONE = 0,
  63. WM_TOOL_DL_ERASE_ALL
  64. } wm_tool_dl_erase_e;
  65. typedef enum {
  66. WM_TOOL_DL_TYPE_IMAGE = 0,
  67. WM_TOOL_DL_TYPE_FLS
  68. } wm_tool_dl_type_e;
  69. typedef enum {
  70. WM_TOOL_LAYOUT_TYPE_1M = 0,
  71. WM_TOOL_LAYOUT_TYPE_2M = 3
  72. } wm_tool_layout_type_e;
  73. typedef enum {
  74. WM_TOOL_ZIP_TYPE_UNCOMPRESS = 0,
  75. WM_TOOL_ZIP_TYPE_COMPRESS
  76. } wm_tool_zip_type_e;
  77. typedef enum {
  78. WM_TOOL_CRC32_REFLECT_OUTPUT = 1,
  79. WM_TOOL_CRC32_REFLECT_INPUT = 2
  80. } wm_tool_crc32_reflect_e;
  81. typedef enum {
  82. WM_TOOL_SHOW_LOG_NONE = 0,
  83. WM_TOOL_SHOW_LOG_STR,
  84. WM_TOOL_SHOW_LOG_HEX
  85. } wm_tool_show_log_e;
  86. typedef struct {
  87. unsigned int magic_no;
  88. unsigned short img_type;
  89. unsigned short zip_type;
  90. unsigned int run_img_addr;
  91. unsigned int run_img_len;
  92. unsigned int img_header_addr;
  93. unsigned int upgrade_img_addr;
  94. unsigned int run_org_checksum;
  95. unsigned int upd_no;
  96. unsigned char ver[WM_TOOL_IMAGE_VERSION_LEN];
  97. unsigned int reserved0;
  98. unsigned int reserved1;
  99. unsigned int next_boot;
  100. unsigned int hd_checksum;
  101. } wm_tool_firmware_booter_t;
  102. const static char *wm_tool_version = "1.0.4";
  103. static int wm_tool_show_usage = 0;
  104. static int wm_tool_list_com = 0;
  105. static int wm_tool_show_ver = 0;
  106. static char wm_tool_serial_path[WM_TOOL_PATH_MAX] = "/dev/ttyS0";
  107. static unsigned int wm_tool_download_serial_rate = WM_TOOL_DEFAULT_BAUD_RATE;
  108. static unsigned int wm_tool_normal_serial_rate = WM_TOOL_DEFAULT_BAUD_RATE;
  109. static wm_tool_dl_action_e wm_tool_dl_action = WM_TOOL_DL_ACTION_NONE;
  110. static wm_tool_dl_erase_e wm_tool_dl_erase = WM_TOOL_DL_ERASE_NONE;
  111. static wm_tool_dl_type_e wm_tool_dl_type = WM_TOOL_DL_TYPE_IMAGE;
  112. static char *wm_tool_download_image = NULL;
  113. static char *wm_tool_input_binary = NULL;
  114. static char *wm_tool_output_image = NULL;
  115. static char *wm_tool_secboot_image = NULL;
  116. static unsigned int wm_tool_src_binary_len = 0;
  117. static unsigned int wm_tool_src_binary_crc = 0;
  118. static int wm_tool_is_debug = 0;
  119. static char wm_tool_image_version[WM_TOOL_IMAGE_VERSION_LEN];
  120. static wm_tool_layout_type_e wm_tool_image_type = WM_TOOL_LAYOUT_TYPE_1M;
  121. static wm_tool_zip_type_e wm_tool_zip_type = WM_TOOL_ZIP_TYPE_COMPRESS;
  122. static unsigned int wm_tool_upd_addr = 0x8090000;
  123. static unsigned int wm_tool_run_addr = 0x8002400;
  124. static unsigned int wm_tool_image_header = 0x8002000;
  125. static unsigned int wm_tool_next_image_header = 0x0;
  126. static unsigned int wm_tool_image_upd_no = 0x0;
  127. static unsigned int wm_tool_file_crc = 0xFFFFFFFF;
  128. static wm_tool_show_log_e wm_tool_show_log_type = WM_TOOL_SHOW_LOG_NONE;
  129. #ifdef __MINGW32__
  130. #ifndef CBR_2000000
  131. #define CBR_2000000 2000000
  132. #endif
  133. #ifndef CBR_1000000
  134. #define CBR_1000000 1000000
  135. #endif
  136. #ifndef CBR_921600
  137. #define CBR_921600 921600
  138. #endif
  139. #ifndef CBR_460800
  140. #define CBR_460800 460800
  141. #endif
  142. static DWORD wm_tool_uart_block = 0;
  143. static HANDLE wm_tool_uart_handle = NULL;
  144. const static int wm_tool_uart_speed_array[] = {CBR_2000000, CBR_1000000, CBR_921600, CBR_460800, CBR_115200, CBR_38400,
  145. CBR_19200, CBR_9600, CBR_4800, CBR_2400, CBR_1200};
  146. #else /* __MINGW32__ */
  147. #ifndef B2000000
  148. #define B2000000 2000000
  149. #endif
  150. #ifndef B1000000
  151. #define B1000000 1000000
  152. #endif
  153. #ifndef B921600
  154. #define B921600 921600
  155. #endif
  156. #ifndef B460800
  157. #define B460800 460800
  158. #endif
  159. static int wm_tool_uart_fd = -1;
  160. static struct termios wm_tool_saved_serial_cfg;
  161. const static int wm_tool_uart_speed_array[] = {B2000000, B1000000, B921600, B460800, B115200, B38400,
  162. B19200, B9600, B4800, B2400, B1200};
  163. #endif /* __MINGW32__ */
  164. const static int wm_tool_uart_name_array[] = {2000000, 1000000, 921600, 460800, 115200, 38400,
  165. 19200, 9600, 4800, 2400, 1200};
  166. const static unsigned char wm_tool_chip_cmd_b115200[] = {0x21, 0x0a, 0x00, 0x97, 0x4b, 0x31, 0x00, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00};
  167. const static unsigned char wm_tool_chip_cmd_b460800[] = {0x21, 0x0a, 0x00, 0x07, 0x00, 0x31, 0x00, 0x00, 0x00, 0x00, 0x08, 0x07, 0x00};
  168. const static unsigned char wm_tool_chip_cmd_b921600[] = {0x21, 0x0a, 0x00, 0x5d, 0x50, 0x31, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0e, 0x00};
  169. const static unsigned char wm_tool_chip_cmd_b1000000[] = {0x21, 0x0a, 0x00, 0x5e, 0x3d, 0x31, 0x00, 0x00, 0x00, 0x40, 0x42, 0x0f, 0x00};
  170. const static unsigned char wm_tool_chip_cmd_b2000000[] = {0x21, 0x0a, 0x00, 0xef, 0x2a, 0x31, 0x00, 0x00, 0x00, 0x80, 0x84, 0x1e, 0x00};
  171. const static unsigned char wm_tool_chip_cmd_get_mac[] = {0x21, 0x06, 0x00, 0xea, 0x2d, 0x38, 0x00, 0x00, 0x00};
  172. const static unsigned char wm_tool_chip_cmd_reset[] = {0x21, 0x06, 0x00, 0xc7, 0x7c, 0x3f, 0x00, 0x00, 0x00};
  173. static const unsigned int wm_tool_crc32_tab[] = {0x00000000L, 0x77073096L, 0xee0e612cL,
  174. 0x990951baL, 0x076dc419L, 0x706af48fL, 0xe963a535L, 0x9e6495a3L,
  175. 0x0edb8832L, 0x79dcb8a4L, 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL,
  176. 0x7eb17cbdL, 0xe7b82d07L, 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L,
  177. 0xf3b97148L, 0x84be41deL, 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L,
  178. 0x83d385c7L, 0x136c9856L, 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL,
  179. 0x14015c4fL, 0x63066cd9L, 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L,
  180. 0x4c69105eL, 0xd56041e4L, 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L,
  181. 0xd20d85fdL, 0xa50ab56bL, 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L,
  182. 0xacbcf940L, 0x32d86ce3L, 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L,
  183. 0x26d930acL, 0x51de003aL, 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L,
  184. 0x56b3c423L, 0xcfba9599L, 0xb8bda50fL, 0x2802b89eL, 0x5f058808L,
  185. 0xc60cd9b2L, 0xb10be924L, 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL,
  186. 0xb6662d3dL, 0x76dc4190L, 0x01db7106L, 0x98d220bcL, 0xefd5102aL,
  187. 0x71b18589L, 0x06b6b51fL, 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L,
  188. 0x0f00f934L, 0x9609a88eL, 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL,
  189. 0x91646c97L, 0xe6635c01L, 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L,
  190. 0xf262004eL, 0x6c0695edL, 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L,
  191. 0x65b0d9c6L, 0x12b7e950L, 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL,
  192. 0x15da2d49L, 0x8cd37cf3L, 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL,
  193. 0xa3bc0074L, 0xd4bb30e2L, 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL,
  194. 0xd3d6f4fbL, 0x4369e96aL, 0x346ed9fcL, 0xad678846L, 0xda60b8d0L,
  195. 0x44042d73L, 0x33031de5L, 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL,
  196. 0x270241aaL, 0xbe0b1010L, 0xc90c2086L, 0x5768b525L, 0x206f85b3L,
  197. 0xb966d409L, 0xce61e49fL, 0x5edef90eL, 0x29d9c998L, 0xb0d09822L,
  198. 0xc7d7a8b4L, 0x59b33d17L, 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL,
  199. 0xedb88320L, 0x9abfb3b6L, 0x03b6e20cL, 0x74b1d29aL, 0xead54739L,
  200. 0x9dd277afL, 0x04db2615L, 0x73dc1683L, 0xe3630b12L, 0x94643b84L,
  201. 0x0d6d6a3eL, 0x7a6a5aa8L, 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L,
  202. 0x7d079eb1L, 0xf00f9344L, 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL,
  203. 0xf762575dL, 0x806567cbL, 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L,
  204. 0x89d32be0L, 0x10da7a5aL, 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L,
  205. 0x17b7be43L, 0x60b08ed5L, 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L,
  206. 0x4fdff252L, 0xd1bb67f1L, 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL,
  207. 0xd80d2bdaL, 0xaf0a1b4cL, 0x36034af6L, 0x41047a60L, 0xdf60efc3L,
  208. 0xa867df55L, 0x316e8eefL, 0x4669be79L, 0xcb61b38cL, 0xbc66831aL,
  209. 0x256fd2a0L, 0x5268e236L, 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L,
  210. 0x5505262fL, 0xc5ba3bbeL, 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L,
  211. 0xc2d7ffa7L, 0xb5d0cf31L, 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L,
  212. 0xec63f226L, 0x756aa39cL, 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL,
  213. 0x72076785L, 0x05005713L, 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL,
  214. 0x0cb61b38L, 0x92d28e9bL, 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L,
  215. 0x86d3d2d4L, 0xf1d4e242L, 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL,
  216. 0xf6b9265bL, 0x6fb077e1L, 0x18b74777L, 0x88085ae6L, 0xff0f6a70L,
  217. 0x66063bcaL, 0x11010b5cL, 0x8f659effL, 0xf862ae69L, 0x616bffd3L,
  218. 0x166ccf45L, 0xa00ae278L, 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L,
  219. 0xa7672661L, 0xd06016f7L, 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL,
  220. 0xd9d65adcL, 0x40df0b66L, 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L,
  221. 0x47b2cf7fL, 0x30b5ffe9L, 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L,
  222. 0x24b4a3a6L, 0xbad03605L, 0xcdd70693L, 0x54de5729L, 0x23d967bfL,
  223. 0xb3667a2eL, 0xc4614ab8L, 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L,
  224. 0xc30c8ea1L, 0x5a05df1bL, 0x2d02ef8dL};
  225. static void wm_tool_signal_proc_entry(void);
  226. static void wm_tool_stdin_to_uart(void);
  227. /* ============================ zlib gzip ================================== */
  228. #define ALLOC(size) zcalloc((voidp)0, 1, size)
  229. #define TRYFREE(p) {if (p) zcfree((voidp)0, p);}
  230. #define BINARY 0
  231. #define ASCII 1
  232. #define UNKNOWN 2
  233. #define STORED_BLOCK 0
  234. #define STATIC_TREES 1
  235. #define DYN_TREES 2
  236. #define REP_3_6 16
  237. #define REPZ_3_10 17
  238. #define REPZ_11_138 18
  239. #define MAX_BL_BITS 7
  240. #define BASE 65521 /* largest prime smaller than 65536 */
  241. #define NMAX 5552
  242. #define DO1(buf) {s1 += *buf++; s2 += s1;}
  243. #define DO2(buf) DO1(buf); DO1(buf);
  244. #define DO4(buf) DO2(buf); DO2(buf);
  245. #define DO8(buf) DO4(buf); DO4(buf);
  246. #define DO16(buf) DO8(buf); DO8(buf);
  247. #define Z_OK 0
  248. #define Z_STREAM_END 1
  249. #define Z_ERRNO (-1)
  250. #define Z_STREAM_ERROR (-2)
  251. #define Z_DATA_ERROR (-3)
  252. #define Z_MEM_ERROR (-4)
  253. #define Z_BUF_ERROR (-5)
  254. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  255. #define Z_BEST_SPEED 1
  256. #define Z_BEST_COMPRESSION 9
  257. #define Z_DEFAULT_COMPRESSION (-1)
  258. #define DEFLATED 8
  259. #ifndef WBITS
  260. # define WBITS 15 /* 32K window */
  261. #endif
  262. #ifndef MEM_LEVEL
  263. # define MEM_LEVEL 8
  264. #endif
  265. #define Z_BUFSIZE 4096
  266. #define GZ_MAGIC_1 0x1f
  267. #define GZ_MAGIC_2 0x8b
  268. #ifndef OS_CODE
  269. # define OS_CODE 0x03 /* assume Unix */
  270. #endif
  271. #ifndef TOO_FAR
  272. # define TOO_FAR 4096
  273. #endif
  274. #define Z_NO_FLUSH 0
  275. #define Z_FINISH 4
  276. #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
  277. #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
  278. #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
  279. #define COMMENT 0x10 /* bit 4 set: file comment present */
  280. #define RESERVED 0xE0 /* bits 5..7: reserved */
  281. #define LENGTH_CODES 29/* number of length codes, not counting the special END_BLOCK code */
  282. #define LITERALS 256/* number of literal bytes 0..255 */
  283. #define L_CODES (LITERALS+1+LENGTH_CODES)/* number of Literal or Length codes, including the END_BLOCK code */
  284. #define D_CODES 30/* number of distance codes */
  285. #define BL_CODES 19/* number of codes used to transfer the bit lengths */
  286. #define HEAP_SIZE (2*L_CODES+1)/* maximum heap size */
  287. #define END_BLOCK 256
  288. #define MAX_BITS 15
  289. #define MAX_MEM_LEVEL 9
  290. #define MIN_MATCH 3
  291. #define MAX_MATCH 258
  292. #define Z_UNKNOWN 2
  293. #define INIT_STATE 42
  294. #define BUSY_STATE 113
  295. #define FINISH_STATE 666
  296. #define NIL 0
  297. #define Z_FILTERED 1
  298. #define Z_HUFFMAN_ONLY 2
  299. #define Z_DEFAULT_STRATEGY 0
  300. #define SMALLEST 1
  301. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  302. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  303. #define ERR_RETURN(strm,err) return (strm->msg=z_errmsg[1-err], err)
  304. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  305. #define put_short(s, w) { \
  306. put_byte(s, (uch)((w) & 0xff)); \
  307. put_byte(s, (uch)((ush)(w) >> 8)); \
  308. }
  309. #define INSERT_STRING(s, str, match_head) \
  310. (UPDATE_HASH(s, s->ins_h, s->window[(str) + MIN_MATCH-1]), \
  311. s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
  312. s->head[s->ins_h] = (str))
  313. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  314. #define check_match(s, start, match, length)
  315. #define d_code(dist) \
  316. ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  317. #define FLUSH_BLOCK_ONLY(s, eof) { \
  318. ct_flush_block(s, (s->block_start >= 0L ? \
  319. (char*)&s->window[(unsigned)s->block_start] : \
  320. (char*)Z_NULL), (long)s->strstart - s->block_start, (eof)); \
  321. s->block_start = s->strstart; \
  322. flush_pending(s->strm); \
  323. }
  324. #define FLUSH_BLOCK(s, eof) { \
  325. FLUSH_BLOCK_ONLY(s, eof); \
  326. if (s->strm->avail_out == 0) return 1; \
  327. }
  328. #define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  329. #define MAX(a,b) (a >= b ? a : b)
  330. #define Buf_size (8 * 2*sizeof(char))
  331. #define smaller(tree, n, m, depth) \
  332. (tree[n].Freq < tree[m].Freq || \
  333. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  334. #define pqremove(s, tree, top) \
  335. {\
  336. top = s->heap[SMALLEST]; \
  337. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  338. pqdownheap(s, tree, SMALLEST); \
  339. }
  340. #ifndef local
  341. # define local static
  342. #endif
  343. #ifndef __P
  344. #define __P(args) args
  345. #endif
  346. #define ZALLOC(strm, items, size) \
  347. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  348. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidp)(addr))
  349. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  350. #define Assert(cond,msg)
  351. #ifndef Byte
  352. typedef unsigned char Byte; /* 8 bits */
  353. #endif
  354. #ifndef uInt
  355. typedef unsigned int uInt; /* may be 16 or 32 bits */
  356. #endif
  357. #ifndef uLong
  358. typedef unsigned long uLong; /* 32 bits or more */
  359. #endif
  360. typedef Byte *voidp;
  361. typedef voidp gzFile;
  362. typedef unsigned char uch;
  363. typedef unsigned long ulg;
  364. typedef unsigned short ush;
  365. typedef ush Pos;
  366. typedef unsigned IPos;
  367. typedef voidp (*alloc_func) __P((voidp opaque, uInt items, uInt size));
  368. typedef void (*free_func) __P((voidp opaque, voidp address));
  369. typedef uLong (*check_func) __P((uLong check, Byte *buf, uInt len));
  370. typedef struct z_stream_s {
  371. Byte *next_in; /* next input byte */
  372. uInt avail_in; /* number of bytes available at next_in */
  373. uLong total_in; /* total nb of input bytes read so far */
  374. Byte *next_out; /* next output byte should be put there */
  375. uInt avail_out; /* remaining free space at next_out */
  376. uLong total_out; /* total nb of bytes output so far */
  377. char *msg; /* last error message, NULL if no error */
  378. struct internal_state *state; /* not visible by applications */
  379. alloc_func zalloc; /* used to allocate the internal state */
  380. free_func zfree; /* used to free the internal state */
  381. voidp opaque; /* private data object passed to zalloc and zfree */
  382. Byte data_type; /* best guess about the data type: ascii or binary */
  383. } z_stream;
  384. typedef struct gz_stream {
  385. z_stream stream;
  386. int z_err; /* error code for last stream operation */
  387. int z_eof; /* set if end of input file */
  388. FILE *file; /* .gz file */
  389. Byte *inbuf; /* input buffer */
  390. Byte *outbuf; /* output buffer */
  391. uLong crc; /* crc32 of uncompressed data */
  392. char *msg; /* error message */
  393. char *path; /* path name for debugging only */
  394. int transparent; /* 1 if input file is not a .gz file */
  395. char mode; /* 'w' or 'r' */
  396. } gz_stream;
  397. /* Data structure describing a single value and its code string. */
  398. typedef struct ct_data_s {
  399. union {
  400. ush freq; /* frequency count */
  401. ush code; /* bit string */
  402. } fc;
  403. union {
  404. ush dad; /* father node in Huffman tree */
  405. ush len; /* length of bit string */
  406. } dl;
  407. } ct_data;
  408. struct static_tree_desc_s {
  409. ct_data *static_tree; /* static tree or NULL */
  410. int *extra_bits; /* extra bits for each code or NULL */
  411. int extra_base; /* base index for extra_bits */
  412. int elems; /* max number of elements in the tree */
  413. int max_length; /* max bit length for the codes */
  414. };
  415. typedef struct static_tree_desc_s static_tree_desc;
  416. typedef struct tree_desc_s {
  417. ct_data *dyn_tree; /* the dynamic tree */
  418. int max_code; /* largest code with non zero frequency */
  419. static_tree_desc *stat_desc; /* the corresponding static tree */
  420. } tree_desc;
  421. typedef struct inflate_huft_s inflate_huft;
  422. struct inflate_huft_s {
  423. union {
  424. struct {
  425. char Exop; /* number of extra bits or operation */
  426. char Bits; /* number of bits in this code or subcode */
  427. } what;
  428. Byte *pad; /* pad structure to a power of 2 (4 bytes for */
  429. } word; /* 16-bit, 8 bytes for 32-bit machines) */
  430. union {
  431. uInt Base; /* literal, length base, or distance base */
  432. inflate_huft *Next; /* pointer to next level of table */
  433. } more;
  434. };
  435. /* inflate codes private state */
  436. struct inflate_codes_state {
  437. /* mode */
  438. enum { /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
  439. START, /* x: set up for LEN */
  440. LEN, /* i: get length/literal/eob next */
  441. LENEXT, /* i: getting length extra (have base) */
  442. DIST, /* i: get distance next */
  443. DISTEXT, /* i: getting distance extra */
  444. COPY, /* o: copying bytes in window, waiting for space */
  445. LIT, /* o: got literal, waiting for output space */
  446. WASH, /* o: got eob, possibly still output waiting */
  447. END, /* x: got eob and all data flushed */
  448. BAD} /* x: got error */
  449. mode; /* current inflate_codes mode */
  450. /* mode dependent information */
  451. uInt len;
  452. union {
  453. struct {
  454. inflate_huft *tree; /* pointer into tree */
  455. uInt need; /* bits needed */
  456. } code; /* if LEN or DIST, where in tree */
  457. uInt lit; /* if LIT, literal */
  458. struct {
  459. uInt get; /* bits to get for extra */
  460. uInt dist; /* distance back to copy from */
  461. } copy; /* if EXT or COPY, where and how much */
  462. } sub; /* submode */
  463. /* mode independent information */
  464. Byte lbits; /* ltree bits decoded per branch */
  465. Byte dbits; /* dtree bits decoder per branch */
  466. inflate_huft *ltree; /* literal/length/eob tree */
  467. inflate_huft *dtree; /* distance tree */
  468. };
  469. /* inflate blocks semi-private state */
  470. struct inflate_blocks_state {
  471. /* mode */
  472. enum {
  473. TYPE, /* get type bits (3, including end bit) */
  474. LENS, /* get lengths for stored */
  475. STORED, /* processing stored block */
  476. TABLE, /* get table lengths */
  477. BTREE, /* get bit lengths tree for a dynamic block */
  478. DTREE, /* get length, distance trees for a dynamic block */
  479. CODES, /* processing fixed or dynamic block */
  480. DRY, /* output remaining window bytes */
  481. DONE, /* finished last block, done */
  482. INF_ERROR}/* got a data error--stuck here */
  483. mode; /* current inflate_block mode */
  484. /* mode dependent information */
  485. union {
  486. uInt left; /* if STORED, bytes left to copy */
  487. struct {
  488. uInt table; /* table lengths (14 bits) */
  489. uInt index; /* index into blens (or border) */
  490. uInt *blens; /* bit lengths of codes */
  491. uInt bb; /* bit length tree depth */
  492. inflate_huft *tb; /* bit length decoding tree */
  493. } trees; /* if DTREE, decoding info for trees */
  494. struct inflate_codes_state
  495. *codes; /* if CODES, current state */
  496. } sub; /* submode */
  497. uInt last; /* true if this block is the last block */
  498. /* mode independent information */
  499. uInt bitk; /* bits in bit buffer */
  500. uLong bitb; /* bit buffer */
  501. Byte *window; /* sliding window */
  502. Byte *end; /* one byte after sliding window */
  503. Byte *read; /* window read pointer */
  504. Byte *write; /* window write pointer */
  505. check_func checkfn; /* check function */
  506. uLong check; /* check on output */
  507. };
  508. typedef struct internal_state {
  509. z_stream *strm; /* pointer back to this zlib stream */
  510. int status; /* as the name implies */
  511. Byte *pending_buf; /* output still pending */
  512. Byte *pending_out; /* next pending byte to output to the stream */
  513. int pending; /* nb of bytes in the pending buffer */
  514. uLong adler; /* adler32 of uncompressed data */
  515. int noheader; /* suppress zlib header and adler32 */
  516. Byte data_type; /* UNKNOWN, BINARY or ASCII */
  517. Byte method; /* STORED (for zip only) or DEFLATED */
  518. /* used by deflate.c: */
  519. uInt w_size; /* LZ77 window size (32K by default) */
  520. uInt w_bits; /* log2(w_size) (8..16) */
  521. uInt w_mask; /* w_size - 1 */
  522. Byte *window;
  523. /* Sliding window. Input bytes are read into the second half of the window,
  524. * and move to the first half later to keep a dictionary of at least wSize
  525. * bytes. With this organization, matches are limited to a distance of
  526. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  527. * performed with a length multiple of the block size. Also, it limits
  528. * the window size to 64K, which is quite useful on MSDOS.
  529. * To do: use the user input buffer as sliding window.
  530. */
  531. ulg window_size;
  532. /* Actual size of window: 2*wSize, except when the user input buffer
  533. * is directly used as sliding window.
  534. */
  535. Pos *prev;
  536. /* Link to older string with same hash index. To limit the size of this
  537. * array to 64K, this link is maintained only for the last 32K strings.
  538. * An index in this array is thus a window index modulo 32K.
  539. */
  540. Pos *head; /* Heads of the hash chains or NIL. */
  541. uInt ins_h; /* hash index of string to be inserted */
  542. uInt hash_size; /* number of elements in hash table */
  543. uInt hash_bits; /* log2(hash_size) */
  544. uInt hash_mask; /* hash_size-1 */
  545. uInt hash_shift;
  546. /* Number of bits by which ins_h must be shifted at each input
  547. * step. It must be such that after MIN_MATCH steps, the oldest
  548. * byte no longer takes part in the hash key, that is:
  549. * hash_shift * MIN_MATCH >= hash_bits
  550. */
  551. long block_start;
  552. /* Window position at the beginning of the current output block. Gets
  553. * negative when the window is moved backwards.
  554. */
  555. uInt match_length; /* length of best match */
  556. IPos prev_match; /* previous match */
  557. int match_available; /* set if previous match exists */
  558. uInt strstart; /* start of string to insert */
  559. uInt match_start; /* start of matching string */
  560. uInt lookahead; /* number of valid bytes ahead in window */
  561. uInt prev_length;
  562. /* Length of the best match at previous step. Matches not greater than this
  563. * are discarded. This is used in the lazy match evaluation.
  564. */
  565. uInt max_chain_length;
  566. /* To speed up deflation, hash chains are never searched beyond this
  567. * length. A higher limit improves compression ratio but degrades the
  568. * speed.
  569. */
  570. uInt max_lazy_match;
  571. /* Attempt to find a better match only when the current match is strictly
  572. * smaller than this value. This mechanism is used only for compression
  573. * levels >= 4.
  574. */
  575. # define max_insert_length max_lazy_match
  576. /* Insert new strings in the hash table only if the match length is not
  577. * greater than this length. This saves time but degrades compression.
  578. * max_insert_length is used only for compression levels <= 3.
  579. */
  580. int level; /* compression level (1..9) */
  581. int strategy; /* favor or force Huffman coding*/
  582. uInt good_match;
  583. /* Use a faster search when the previous match is longer than this */
  584. int nice_match; /* Stop searching when current match exceeds this */
  585. /* used by trees.c: */
  586. ct_data dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  587. ct_data dyn_dtree[2*D_CODES+1]; /* distance tree */
  588. ct_data bl_tree[2*BL_CODES+1]; /* Huffman tree for the bit lengths */
  589. tree_desc l_desc; /* descriptor for literal tree */
  590. tree_desc d_desc; /* descriptor for distance tree */
  591. tree_desc bl_desc; /* descriptor for bit length tree */
  592. ush bl_count[MAX_BITS+1];
  593. /* number of codes at each bit length for an optimal tree */
  594. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  595. int heap_len; /* number of elements in the heap */
  596. int heap_max; /* element of largest frequency */
  597. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  598. * The same heap array is used to build all trees.
  599. */
  600. uch depth[2*L_CODES+1];
  601. /* Depth of each subtree used as tie breaker for trees of equal frequency
  602. */
  603. uch *l_buf; /* buffer for literals or lengths */
  604. uInt lit_bufsize;
  605. /* Size of match buffer for literals/lengths. There are 4 reasons for
  606. * limiting lit_bufsize to 64K:
  607. * - frequencies can be kept in 16 bit counters
  608. * - if compression is not successful for the first block, all input
  609. * data is still in the window so we can still emit a stored block even
  610. * when input comes from standard input. (This can also be done for
  611. * all blocks if lit_bufsize is not greater than 32K.)
  612. * - if compression is not successful for a file smaller than 64K, we can
  613. * even emit a stored file instead of a stored block (saving 5 bytes).
  614. * This is applicable only for zip (not gzip or zlib).
  615. * - creating new Huffman trees less frequently may not provide fast
  616. * adaptation to changes in the input data statistics. (Take for
  617. * example a binary file with poorly compressible code followed by
  618. * a highly compressible string table.) Smaller buffer sizes give
  619. * fast adaptation but have of course the overhead of transmitting
  620. * trees more frequently.
  621. * - I can't count above 4
  622. */
  623. uInt last_lit; /* running index in l_buf */
  624. ush *d_buf;
  625. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  626. * the same number of elements. To use different lengths, an extra flag
  627. * array would be necessary.
  628. */
  629. ulg opt_len; /* bit length of current block with optimal trees */
  630. ulg static_len; /* bit length of current block with static trees */
  631. ulg compressed_len; /* total bit length of compressed file */
  632. uInt matches; /* number of string matches in current block */
  633. #ifdef DEBUG
  634. ulg bits_sent; /* bit length of the compressed data */
  635. #endif
  636. ush bi_buf;
  637. /* Output buffer. bits are inserted starting at the bottom (least
  638. * significant bits).
  639. */
  640. int bi_valid;
  641. /* Number of valid bits in bi_buf. All bits above the last valid bit
  642. * are always zero.
  643. */
  644. /* mode */
  645. enum {
  646. METHOD, /* waiting for method byte */
  647. FLAG, /* waiting for flag byte */
  648. //START, /* make new blocks state */
  649. BLOCKS, /* decompressing blocks */
  650. CHECK4, /* four check bytes to go */
  651. CHECK3, /* three check bytes to go */
  652. CHECK2, /* two check bytes to go */
  653. CHECK1, /* one check byte to go */
  654. //DONE, /* finished check, done */
  655. //INF_ERROR/* got an error--stay here */
  656. }
  657. mode; /* current inflate mode */
  658. /* mode dependent information */
  659. union {
  660. uInt method; /* if FLAGS, method byte */
  661. struct inflate_blocks_state
  662. *blocks; /* if BLOCKS, current state */
  663. struct {
  664. uLong was; /* computed check value */
  665. uLong need; /* stream check value */
  666. } check; /* if CHECK, check values to compare */
  667. } sub; /* submode */
  668. /* mode independent information */
  669. int nowrap; /* flag for no wrapper */
  670. uInt wbits; /* log2(window size) (8..15, defaults to 15) */
  671. } deflate_state;
  672. typedef struct config_s {
  673. ush good_length; /* reduce lazy search above this match length */
  674. ush max_lazy; /* do not perform lazy search above this match length */
  675. ush nice_length; /* quit search above this match length */
  676. ush max_chain;
  677. } config;
  678. char *z_errmsg[] = {
  679. "stream end", /* Z_STREAM_END 1 */
  680. "", /* Z_OK 0 */
  681. "file error", /* Z_ERRNO (-1) */
  682. "stream error", /* Z_STREAM_ERROR (-2) */
  683. "data error", /* Z_DATA_ERROR (-3) */
  684. "insufficient memory", /* Z_MEM_ERROR (-4) */
  685. "buffer error", /* Z_BUF_ERROR (-5) */
  686. ""};
  687. local int base_length[LENGTH_CODES];
  688. local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  689. = {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};
  690. local uch length_code[MAX_MATCH-MIN_MATCH+1];
  691. local int base_dist[D_CODES];
  692. local int extra_dbits[D_CODES] /* extra bits for each distance code */
  693. = {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};
  694. local ct_data static_ltree[L_CODES+2];
  695. local uch dist_code[512];
  696. local int base_dist[D_CODES];
  697. local ct_data static_dtree[D_CODES];
  698. local static_tree_desc static_l_desc =
  699. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  700. local static_tree_desc static_d_desc =
  701. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  702. local int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  703. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  704. local static_tree_desc static_bl_desc =
  705. {(ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  706. local uch bl_order[BL_CODES]
  707. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  708. local config configuration_table[10] = {
  709. /* good lazy nice chain */
  710. /* 0 */ {0, 0, 0, 0}, /* store only */
  711. /* 1 */ {4, 4, 8, 4}, /* maximum speed, no lazy matches */
  712. /* 2 */ {4, 5, 16, 8},
  713. /* 3 */ {4, 6, 32, 32},
  714. /* 4 */ {4, 4, 16, 16}, /* lazy matches */
  715. /* 5 */ {8, 16, 32, 32},
  716. /* 6 */ {8, 16, 128, 128},
  717. /* 7 */ {8, 32, 128, 256},
  718. /* 8 */ {32, 128, 258, 1024},
  719. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  720. #define FIXEDH 530 /* number of hufts used by fixed tables */
  721. local inflate_huft fixed_mem[FIXEDH];
  722. #define next more.Next
  723. #define Freq fc.freq
  724. #define Code fc.code
  725. #define Dad dl.dad
  726. #define Len dl.len
  727. local voidp zcalloc (opaque, items, size)
  728. voidp opaque;
  729. unsigned items;
  730. unsigned size;
  731. {
  732. return calloc(items, size);
  733. }
  734. local void zcfree (opaque, ptr)
  735. voidp opaque;
  736. voidp ptr;
  737. {
  738. free(ptr);
  739. }
  740. local uLong crc32(crc, buf, len)
  741. uLong crc;
  742. Byte *buf;
  743. uInt len;
  744. {
  745. if (buf == Z_NULL) return 0L;
  746. crc = crc ^ 0xffffffffL;
  747. if (len) do {
  748. crc = wm_tool_crc32_tab[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
  749. } while (--len);
  750. return crc ^ 0xffffffffL;
  751. }
  752. local void zmemcpy(dest, source, len)
  753. Byte* dest;
  754. Byte* source;
  755. uInt len;
  756. {
  757. if (len == 0) return;
  758. do {
  759. *dest++ = *source++; /* ??? to be unrolled */
  760. } while (--len != 0);
  761. }
  762. local void zmemzero(dest, len)
  763. Byte* dest;
  764. uInt len;
  765. {
  766. if (len == 0) return;
  767. do {
  768. *dest++ = 0; /* ??? to be unrolled */
  769. } while (--len != 0);
  770. }
  771. local uLong adler32(adler, buf, len)
  772. uLong adler;
  773. Byte *buf;
  774. uInt len;
  775. {
  776. unsigned long s1 = adler & 0xffff;
  777. unsigned long s2 = (adler >> 16) & 0xffff;
  778. int k;
  779. if (buf == Z_NULL) return 1L;
  780. while (len > 0) {
  781. k = len < NMAX ? len : NMAX;
  782. len -= k;
  783. while (k >= 16) {
  784. DO16(buf);
  785. k -= 16;
  786. }
  787. if (k != 0) do {
  788. DO1(buf);
  789. } while (--k);
  790. s1 %= BASE;
  791. s2 %= BASE;
  792. }
  793. return (s2 << 16) | s1;
  794. }
  795. local int read_buf(strm, buf, size)
  796. z_stream *strm;
  797. char *buf;
  798. unsigned size;
  799. {
  800. unsigned len = strm->avail_in;
  801. if (len > size) len = size;
  802. if (len == 0) return 0;
  803. strm->avail_in -= len;
  804. if (!strm->state->noheader) {
  805. strm->state->adler = adler32(strm->state->adler, strm->next_in, len);
  806. }
  807. zmemcpy((Byte *)buf, strm->next_in, len);
  808. strm->next_in += len;
  809. strm->total_in += len;
  810. return (int)len;
  811. }
  812. local int inflate_trees_free(t, z)
  813. inflate_huft *t; /* table to free */
  814. z_stream *z; /* for zfree function */
  815. /* Free the malloc'ed tables built by huft_build(), which makes a linked
  816. list of the tables it made, with the links in a dummy first entry of
  817. each table. */
  818. {
  819. register inflate_huft *p, *q;
  820. /* Don't free fixed trees */
  821. if (t >= fixed_mem && t <= fixed_mem + FIXEDH)
  822. return Z_OK;
  823. /* Go through linked list, freeing from the malloced (t[-1]) address. */
  824. p = t;
  825. while (p != Z_NULL)
  826. {
  827. q = (--p)->next;
  828. ZFREE(z,p);
  829. p = q;
  830. }
  831. return Z_OK;
  832. }
  833. local void inflate_codes_free(c, z)
  834. struct inflate_codes_state *c;
  835. z_stream *z;
  836. {
  837. inflate_trees_free(c->dtree, z);
  838. inflate_trees_free(c->ltree, z);
  839. ZFREE(z, c);
  840. }
  841. local int inflate_blocks_free(s, z, c)
  842. struct inflate_blocks_state *s;
  843. z_stream *z;
  844. uLong *c;
  845. {
  846. if (s->checkfn != Z_NULL)
  847. *c = s->check;
  848. if (s->mode == BTREE || s->mode == DTREE)
  849. ZFREE(z, s->sub.trees.blens);
  850. if (s->mode == CODES)
  851. inflate_codes_free(s->sub.codes, z);
  852. ZFREE(z, s->window);
  853. ZFREE(z, s);
  854. return Z_OK;
  855. }
  856. local int deflateEnd (strm)
  857. z_stream *strm;
  858. {
  859. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  860. TRY_FREE(strm, strm->state->window);
  861. TRY_FREE(strm, strm->state->prev);
  862. TRY_FREE(strm, strm->state->head);
  863. TRY_FREE(strm, strm->state->pending_buf);
  864. ZFREE(strm, strm->state);
  865. strm->state = Z_NULL;
  866. return Z_OK;
  867. }
  868. local int inflateEnd(z)
  869. z_stream *z;
  870. {
  871. uLong c;
  872. if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
  873. return Z_STREAM_ERROR;
  874. if (z->state->mode == BLOCKS)
  875. inflate_blocks_free(z->state->sub.blocks, z, &c);
  876. ZFREE(z, z->state);
  877. z->state = Z_NULL;
  878. return Z_OK;
  879. }
  880. local int destroy (s)
  881. gz_stream *s;
  882. {
  883. int err = Z_OK;
  884. if (!s) return Z_STREAM_ERROR;
  885. TRYFREE(s->inbuf);
  886. TRYFREE(s->outbuf);
  887. TRYFREE((voidp)s->path);
  888. TRYFREE((voidp)s->msg);
  889. if (s->stream.state != NULL) {
  890. if (s->mode == 'w') {
  891. err = deflateEnd(&(s->stream));
  892. } else if (s->mode == 'r') {
  893. err = inflateEnd(&(s->stream));
  894. }
  895. }
  896. if (s->file != NULL && fclose(s->file)) {
  897. err = Z_ERRNO;
  898. }
  899. if (s->z_err < 0) err = s->z_err;
  900. zcfree((voidp)0, (voidp)s);
  901. return err;
  902. }
  903. local void putLong (file, x)
  904. FILE *file;
  905. uLong x;
  906. {
  907. int n;
  908. for (n = 0; n < 4; n++) {
  909. fputc((int)(x & 0xff), file);
  910. x >>= 8;
  911. }
  912. }
  913. local uLong getLong (buf)
  914. Byte *buf;
  915. {
  916. uLong x = 0;
  917. Byte *p = buf+4;
  918. do {
  919. x <<= 8;
  920. x |= *--p;
  921. } while (p != buf);
  922. return x;
  923. }
  924. local unsigned bi_reverse(code, len)
  925. unsigned code; /* the value to invert */
  926. int len; /* its bit length */
  927. {
  928. register unsigned res = 0;
  929. do {
  930. res |= code & 1;
  931. code >>= 1, res <<= 1;
  932. } while (--len > 0);
  933. return res >> 1;
  934. }
  935. local void gen_codes (tree, max_code, bl_count)
  936. ct_data *tree; /* the tree to decorate */
  937. int max_code; /* largest code with non zero frequency */
  938. ush bl_count[]; /* number of codes at each bit length */
  939. {
  940. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  941. ush code = 0; /* running code value */
  942. int bits; /* bit index */
  943. int n; /* code index */
  944. /* The distribution counts are first used to generate the code values
  945. * without bit reversal.
  946. */
  947. for (bits = 1; bits <= MAX_BITS; bits++) {
  948. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  949. }
  950. /* Check that the bit counts in bl_count are consistent. The last code
  951. * must be all ones.
  952. */
  953. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  954. "inconsistent bit counts");
  955. for (n = 0; n <= max_code; n++) {
  956. int len = tree[n].Len;
  957. if (len == 0) continue;
  958. /* Now reverse the bits */
  959. tree[n].Code = bi_reverse(next_code[len]++, len);
  960. }
  961. }
  962. local void ct_static_init()
  963. {
  964. int n; /* iterates over tree elements */
  965. int bits; /* bit counter */
  966. int length; /* length value */
  967. int code; /* code value */
  968. int dist; /* distance index */
  969. ush bl_count[MAX_BITS+1];
  970. /* number of codes at each bit length for an optimal tree */
  971. /* Initialize the mapping length (0..255) -> length code (0..28) */
  972. length = 0;
  973. for (code = 0; code < LENGTH_CODES-1; code++) {
  974. base_length[code] = length;
  975. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  976. length_code[length++] = (uch)code;
  977. }
  978. }
  979. Assert (length == 256, "ct_static_init: length != 256");
  980. /* Note that the length 255 (match length 258) can be represented
  981. * in two different ways: code 284 + 5 bits or code 285, so we
  982. * overwrite length_code[255] to use the best encoding:
  983. */
  984. length_code[length-1] = (uch)code;
  985. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  986. dist = 0;
  987. for (code = 0 ; code < 16; code++) {
  988. base_dist[code] = dist;
  989. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  990. dist_code[dist++] = (uch)code;
  991. }
  992. }
  993. Assert (dist == 256, "ct_static_init: dist != 256");
  994. dist >>= 7; /* from now on, all distances are divided by 128 */
  995. for ( ; code < D_CODES; code++) {
  996. base_dist[code] = dist << 7;
  997. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  998. dist_code[256 + dist++] = (uch)code;
  999. }
  1000. }
  1001. Assert (dist == 256, "ct_static_init: 256+dist != 512");
  1002. /* Construct the codes of the static literal tree */
  1003. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  1004. n = 0;
  1005. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  1006. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  1007. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  1008. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  1009. /* Codes 286 and 287 do not exist, but we must include them in the
  1010. * tree construction to get a canonical Huffman tree (longest code
  1011. * all ones)
  1012. */
  1013. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  1014. /* The static distance tree is trivial: */
  1015. for (n = 0; n < D_CODES; n++) {
  1016. static_dtree[n].Len = 5;
  1017. static_dtree[n].Code = bi_reverse(n, 5);
  1018. }
  1019. }
  1020. local void init_block(s)
  1021. deflate_state *s;
  1022. {
  1023. int n; /* iterates over tree elements */
  1024. /* Initialize the trees. */
  1025. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  1026. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  1027. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  1028. s->dyn_ltree[END_BLOCK].Freq = 1;
  1029. s->opt_len = s->static_len = 0L;
  1030. s->last_lit = s->matches = 0;
  1031. }
  1032. local void ct_init(s)
  1033. deflate_state *s;
  1034. {
  1035. if (static_dtree[0].Len == 0) {
  1036. ct_static_init(); /* To do: at compile time */
  1037. }
  1038. s->compressed_len = 0L;
  1039. s->l_desc.dyn_tree = s->dyn_ltree;
  1040. s->l_desc.stat_desc = &static_l_desc;
  1041. s->d_desc.dyn_tree = s->dyn_dtree;
  1042. s->d_desc.stat_desc = &static_d_desc;
  1043. s->bl_desc.dyn_tree = s->bl_tree;
  1044. s->bl_desc.stat_desc = &static_bl_desc;
  1045. s->bi_buf = 0;
  1046. s->bi_valid = 0;
  1047. #ifdef DEBUG
  1048. s->bits_sent = 0L;
  1049. #endif
  1050. /* Initialize the first block of the first file: */
  1051. init_block(s);
  1052. }
  1053. local void lm_init (s)
  1054. deflate_state *s;
  1055. {
  1056. register unsigned j;
  1057. s->window_size = (ulg)2L*s->w_size;
  1058. /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  1059. * prev[] will be initialized on the fly.
  1060. */
  1061. s->head[s->hash_size-1] = NIL;
  1062. zmemzero((unsigned char*)s->head, (unsigned int)(s->hash_size-1)*sizeof(*s->head));
  1063. /* Set the default configuration parameters:
  1064. */
  1065. s->max_lazy_match = configuration_table[s->level].max_lazy;
  1066. s->good_match = configuration_table[s->level].good_length;
  1067. s->nice_match = configuration_table[s->level].nice_length;
  1068. s->max_chain_length = configuration_table[s->level].max_chain;
  1069. s->strstart = 0;
  1070. s->block_start = 0L;
  1071. s->lookahead = 0;
  1072. s->match_length = MIN_MATCH-1;
  1073. s->match_available = 0;
  1074. #ifdef ASMV
  1075. match_init(); /* initialize the asm code */
  1076. #endif
  1077. s->ins_h = 0;
  1078. for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(s, s->ins_h, s->window[j]);
  1079. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  1080. * not important since only literal bytes will be emitted.
  1081. */
  1082. }
  1083. local int deflateReset (strm)
  1084. z_stream *strm;
  1085. {
  1086. deflate_state *s;
  1087. if (strm == Z_NULL || strm->state == Z_NULL ||
  1088. strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
  1089. strm->total_in = strm->total_out = 0;
  1090. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  1091. strm->data_type = Z_UNKNOWN;
  1092. s = (deflate_state *)strm->state;
  1093. s->pending = 0;
  1094. s->pending_out = s->pending_buf;
  1095. s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  1096. s->adler = 1;
  1097. ct_init(s);
  1098. lm_init(s);
  1099. return Z_OK;
  1100. }
  1101. local int deflateInit2 (strm, level, method, windowBits, memLevel, strategy)
  1102. z_stream *strm;
  1103. int level;
  1104. int method;
  1105. int windowBits;
  1106. int memLevel;
  1107. int strategy;
  1108. {
  1109. deflate_state *s;
  1110. int noheader = 0;
  1111. if (strm == Z_NULL) return Z_STREAM_ERROR;
  1112. strm->msg = Z_NULL;
  1113. if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc;
  1114. if (strm->zfree == Z_NULL) strm->zfree = zcfree;
  1115. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  1116. if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  1117. noheader = 1;
  1118. windowBits = -windowBits;
  1119. }
  1120. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
  1121. windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
  1122. return Z_STREAM_ERROR;
  1123. }
  1124. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  1125. if (s == Z_NULL) return Z_MEM_ERROR;
  1126. strm->state = (struct internal_state *)s;
  1127. s->strm = strm;
  1128. s->noheader = noheader;
  1129. s->w_bits = windowBits;
  1130. s->w_size = 1 << s->w_bits;
  1131. s->w_mask = s->w_size - 1;
  1132. s->hash_bits = memLevel + 7;
  1133. s->hash_size = 1 << s->hash_bits;
  1134. s->hash_mask = s->hash_size - 1;
  1135. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  1136. s->window = (Byte*) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  1137. s->prev = (Pos*) ZALLOC(strm, s->w_size, sizeof(Pos));
  1138. s->head = (Pos*) ZALLOC(strm, s->hash_size, sizeof(Pos));
  1139. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  1140. s->pending_buf = (uch*) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
  1141. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  1142. s->pending_buf == Z_NULL) {
  1143. strm->msg = z_errmsg[1-Z_MEM_ERROR];
  1144. deflateEnd (strm);
  1145. return Z_MEM_ERROR;
  1146. }
  1147. s->d_buf = (ush*) &(s->pending_buf[s->lit_bufsize]);
  1148. s->l_buf = (uch*) &(s->pending_buf[3*s->lit_bufsize]);
  1149. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  1150. * output size for (length,distance) codes is <= 32 bits (worst case
  1151. * is 15+15+13=33).
  1152. */
  1153. s->level = level;
  1154. s->strategy = strategy;
  1155. s->method = (Byte)method;
  1156. return deflateReset(strm);
  1157. }
  1158. local int inflateInit2(z, w)
  1159. z_stream *z;
  1160. int w;
  1161. {
  1162. /* initialize state */
  1163. if (z == Z_NULL)
  1164. return Z_STREAM_ERROR;
  1165. if (z->zalloc == Z_NULL) z->zalloc = zcalloc;
  1166. if (z->zfree == Z_NULL) z->zfree = zcfree;
  1167. z->total_in = z->total_out = 0;
  1168. z->msg = Z_NULL;
  1169. if ((z->state = (struct internal_state *)
  1170. ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
  1171. return Z_MEM_ERROR;
  1172. z->state->mode = METHOD;
  1173. /* handle undocumented nowrap option (no zlib header or check) */
  1174. z->state->nowrap = 0;
  1175. if (w < 0)
  1176. {
  1177. w = - w;
  1178. z->state->nowrap = 1;
  1179. z->state->mode = START;
  1180. }
  1181. /* set window size */
  1182. if (w < 8 || w > 15)
  1183. {
  1184. inflateEnd(z);
  1185. return Z_STREAM_ERROR;
  1186. }
  1187. z->state->wbits = w;
  1188. return Z_OK;
  1189. }
  1190. local void putShortMSB (s, b)
  1191. deflate_state *s;
  1192. uInt b;
  1193. {
  1194. put_byte(s, (Byte)(b >> 8));
  1195. put_byte(s, (Byte)(b & 0xff));
  1196. }
  1197. local void flush_pending(strm)
  1198. z_stream *strm;
  1199. {
  1200. unsigned len = strm->state->pending;
  1201. if (len > strm->avail_out) len = strm->avail_out;
  1202. if (len == 0) return;
  1203. zmemcpy(strm->next_out, strm->state->pending_out, len);
  1204. strm->next_out += len;
  1205. strm->state->pending_out += len;
  1206. strm->total_out += len;
  1207. strm->avail_out -= len;
  1208. strm->state->pending -= len;
  1209. if (strm->state->pending == 0) {
  1210. strm->state->pending_out = strm->state->pending_buf;
  1211. }
  1212. }
  1213. local void fill_window(s)
  1214. deflate_state *s;
  1215. {
  1216. register unsigned n, m;
  1217. unsigned more; /* Amount of free space at the end of the window. */
  1218. do {
  1219. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  1220. /* Deal with !@#$% 64K limit: */
  1221. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  1222. more = s->w_size;
  1223. } else if (more == (unsigned)(-1)) {
  1224. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  1225. * and lookahead == 1 (input done one byte at time)
  1226. */
  1227. more--;
  1228. /* If the window is almost full and there is insufficient lookahead,
  1229. * move the upper half to the lower one to make room in the upper half.
  1230. */
  1231. } else if (s->strstart >= s->w_size+MAX_DIST(s)) {
  1232. /* By the IN assertion, the window is not empty so we can't confuse
  1233. * more == 0 with more == 64K on a 16 bit machine.
  1234. */
  1235. memcpy((char*)s->window, (char*)s->window+s->w_size,
  1236. (unsigned)s->w_size);
  1237. s->match_start -= s->w_size;
  1238. s->strstart -= s->w_size; /* we now have strstart >= MAX_DIST */
  1239. s->block_start -= (long) s->w_size;
  1240. for (n = 0; n < s->hash_size; n++) {
  1241. m = s->head[n];
  1242. s->head[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
  1243. }
  1244. for (n = 0; n < s->w_size; n++) {
  1245. m = s->prev[n];
  1246. s->prev[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
  1247. /* If n is not on any hash chain, prev[n] is garbage but
  1248. * its value will never be used.
  1249. */
  1250. }
  1251. more += s->w_size;
  1252. }
  1253. if (s->strm->avail_in == 0) return;
  1254. /* If there was no sliding:
  1255. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1256. * more == window_size - lookahead - strstart
  1257. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1258. * => more >= window_size - 2*WSIZE + 2
  1259. * In the BIG_MEM or MMAP case (not yet supported),
  1260. * window_size == input_size + MIN_LOOKAHEAD &&
  1261. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1262. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1263. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1264. */
  1265. Assert(more >= 2, "more < 2");
  1266. n = read_buf(s->strm, (char*)s->window + s->strstart + s->lookahead,
  1267. more);
  1268. s->lookahead += n;
  1269. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1270. }
  1271. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1272. * match.S. The code will be functionally equivalent.
  1273. */
  1274. local int longest_match(s, cur_match)
  1275. deflate_state *s;
  1276. IPos cur_match; /* current match */
  1277. {
  1278. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  1279. register Byte *scan = s->window + s->strstart; /* current string */
  1280. register Byte *match; /* matched string */
  1281. register int len; /* length of current match */
  1282. int best_len = s->prev_length; /* best match length so far */
  1283. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  1284. s->strstart - (IPos)MAX_DIST(s) : NIL;
  1285. /* Stop when cur_match becomes <= limit. To simplify the code,
  1286. * we prevent matches with the string of window index 0.
  1287. */
  1288. #ifdef UNALIGNED_OK
  1289. /* Compare two bytes at a time. Note: this is not always beneficial.
  1290. * Try with and without -DUNALIGNED_OK to check.
  1291. */
  1292. register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
  1293. register ush scan_start = *(ush*)scan;
  1294. register ush scan_end = *(ush*)(scan+best_len-1);
  1295. #else
  1296. register Byte *strend = s->window + s->strstart + MAX_MATCH;
  1297. register Byte scan_end1 = scan[best_len-1];
  1298. register Byte scan_end = scan[best_len];
  1299. #endif
  1300. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1301. * It is easy to get rid of this optimization if necessary.
  1302. */
  1303. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1304. /* Do not waste too much time if we already have a good match: */
  1305. if (s->prev_length >= s->good_match) {
  1306. chain_length >>= 2;
  1307. }
  1308. Assert(s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1309. do {
  1310. Assert(cur_match < s->strstart, "no future");
  1311. match = s->window + cur_match;
  1312. /* Skip to next match if the match length cannot increase
  1313. * or if the match length is less than 2:
  1314. */
  1315. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  1316. /* This code assumes sizeof(unsigned short) == 2. Do not use
  1317. * UNALIGNED_OK if your compiler uses a different size.
  1318. */
  1319. if (*(ush*)(match+best_len-1) != scan_end ||
  1320. *(ush*)match != scan_start) continue;
  1321. /* It is not necessary to compare scan[2] and match[2] since they are
  1322. * always equal when the other bytes match, given that the hash keys
  1323. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1324. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  1325. * lookahead only every 4th comparison; the 128th check will be made
  1326. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1327. * necessary to put more guard bytes at the end of the window, or
  1328. * to check more often for insufficient lookahead.
  1329. */
  1330. scan++, match++;
  1331. do {
  1332. } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  1333. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  1334. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  1335. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  1336. scan < strend);
  1337. /* The funny "do {}" generates better code on most compilers */
  1338. /* Here, scan <= window+strstart+257 */
  1339. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1340. if (*scan == *match) scan++;
  1341. len = (MAX_MATCH - 1) - (int)(strend-scan);
  1342. scan = strend - (MAX_MATCH-1);
  1343. #else /* UNALIGNED_OK */
  1344. if (match[best_len] != scan_end ||
  1345. match[best_len-1] != scan_end1 ||
  1346. *match != *scan ||
  1347. *++match != scan[1]) continue;
  1348. /* The check at best_len-1 can be removed because it will be made
  1349. * again later. (This heuristic is not always a win.)
  1350. * It is not necessary to compare scan[2] and match[2] since they
  1351. * are always equal when the other bytes match, given that
  1352. * the hash keys are equal and that HASH_BITS >= 8.
  1353. */
  1354. scan += 2, match++;
  1355. /* We check for insufficient lookahead only every 8th comparison;
  1356. * the 256th check will be made at strstart+258.
  1357. */
  1358. do {
  1359. } while (*++scan == *++match && *++scan == *++match &&
  1360. *++scan == *++match && *++scan == *++match &&
  1361. *++scan == *++match && *++scan == *++match &&
  1362. *++scan == *++match && *++scan == *++match &&
  1363. scan < strend);
  1364. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1365. len = MAX_MATCH - (int)(strend - scan);
  1366. scan = strend - MAX_MATCH;
  1367. #endif /* UNALIGNED_OK */
  1368. if (len > best_len) {
  1369. s->match_start = cur_match;
  1370. best_len = len;
  1371. if (len >= s->nice_match) break;
  1372. #ifdef UNALIGNED_OK
  1373. scan_end = *(ush*)(scan+best_len-1);
  1374. #else
  1375. scan_end1 = scan[best_len-1];
  1376. scan_end = scan[best_len];
  1377. #endif
  1378. }
  1379. } while ((cur_match = s->prev[cur_match & s->w_mask]) > limit
  1380. && --chain_length != 0);
  1381. return best_len;
  1382. }
  1383. local int ct_tally (s, dist, lc)
  1384. deflate_state *s;
  1385. int dist; /* distance of matched string */
  1386. int lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  1387. {
  1388. s->d_buf[s->last_lit] = (ush)dist;
  1389. s->l_buf[s->last_lit++] = (uch)lc;
  1390. if (dist == 0) {
  1391. /* lc is the unmatched char */
  1392. s->dyn_ltree[lc].Freq++;
  1393. } else {
  1394. s->matches++;
  1395. /* Here, lc is the match length - MIN_MATCH */
  1396. dist--; /* dist = match distance - 1 */
  1397. Assert((ush)dist < (ush)MAX_DIST(s) &&
  1398. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  1399. (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match");
  1400. s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  1401. s->dyn_dtree[d_code(dist)].Freq++;
  1402. }
  1403. /* Try to guess if it is profitable to stop the current block here */
  1404. if (s->level > 2 && (s->last_lit & 0xfff) == 0) {
  1405. /* Compute an upper bound for the compressed length */
  1406. ulg out_length = (ulg)s->last_lit*8L;
  1407. ulg in_length = (ulg)s->strstart - s->block_start;
  1408. int dcode;
  1409. for (dcode = 0; dcode < D_CODES; dcode++) {
  1410. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  1411. (5L+extra_dbits[dcode]);
  1412. }
  1413. out_length >>= 3;
  1414. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  1415. }
  1416. return (s->last_lit == s->lit_bufsize-1);
  1417. /* We avoid equality with lit_bufsize because of wraparound at 64K
  1418. * on 16 bit machines and because stored blocks are restricted to
  1419. * 64K-1 bytes.
  1420. */
  1421. }
  1422. local void set_data_type(s)
  1423. deflate_state *s;
  1424. {
  1425. int n = 0;
  1426. unsigned ascii_freq = 0;
  1427. unsigned bin_freq = 0;
  1428. while (n < 7) bin_freq += s->dyn_ltree[n++].Freq;
  1429. while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq;
  1430. while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
  1431. s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? BINARY : ASCII);
  1432. }
  1433. local void pqdownheap(s, tree, k)
  1434. deflate_state *s;
  1435. ct_data *tree; /* the tree to restore */
  1436. int k; /* node to move down */
  1437. {
  1438. int v = s->heap[k];
  1439. int j = k << 1; /* left son of k */
  1440. while (j <= s->heap_len) {
  1441. /* Set j to the smallest of the two sons: */
  1442. if (j < s->heap_len &&
  1443. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  1444. j++;
  1445. }
  1446. /* Exit if v is smaller than both sons */
  1447. if (smaller(tree, v, s->heap[j], s->depth)) break;
  1448. /* Exchange v with the smallest son */
  1449. s->heap[k] = s->heap[j]; k = j;
  1450. /* And continue down the tree, setting j to the left son of k */
  1451. j <<= 1;
  1452. }
  1453. s->heap[k] = v;
  1454. }
  1455. local void gen_bitlen(s, desc)
  1456. deflate_state *s;
  1457. tree_desc *desc; /* the tree descriptor */
  1458. {
  1459. ct_data *tree = desc->dyn_tree;
  1460. int max_code = desc->max_code;
  1461. ct_data *stree = desc->stat_desc->static_tree;
  1462. int *extra = desc->stat_desc->extra_bits;
  1463. int base = desc->stat_desc->extra_base;
  1464. int max_length = desc->stat_desc->max_length;
  1465. int h; /* heap index */
  1466. int n, m; /* iterate over the tree elements */
  1467. int bits; /* bit length */
  1468. int xbits; /* extra bits */
  1469. ush f; /* frequency */
  1470. int overflow = 0; /* number of elements with bit length too large */
  1471. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  1472. /* In a first pass, compute the optimal bit lengths (which may
  1473. * overflow in the case of the bit length tree).
  1474. */
  1475. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  1476. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  1477. n = s->heap[h];
  1478. bits = tree[tree[n].Dad].Len + 1;
  1479. if (bits > max_length) bits = max_length, overflow++;
  1480. tree[n].Len = (ush)bits;
  1481. /* We overwrite tree[n].Dad which is no longer needed */
  1482. if (n > max_code) continue; /* not a leaf node */
  1483. s->bl_count[bits]++;
  1484. xbits = 0;
  1485. if (n >= base) xbits = extra[n-base];
  1486. f = tree[n].Freq;
  1487. s->opt_len += (ulg)f * (bits + xbits);
  1488. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  1489. }
  1490. if (overflow == 0) return;
  1491. /* This happens for example on obj2 and pic of the Calgary corpus */
  1492. /* Find the first bit length which could increase: */
  1493. do {
  1494. bits = max_length-1;
  1495. while (s->bl_count[bits] == 0) bits--;
  1496. s->bl_count[bits]--; /* move one leaf down the tree */
  1497. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  1498. s->bl_count[max_length]--;
  1499. /* The brother of the overflow item also moves one step up,
  1500. * but this does not affect bl_count[max_length]
  1501. */
  1502. overflow -= 2;
  1503. } while (overflow > 0);
  1504. /* Now recompute all bit lengths, scanning in increasing frequency.
  1505. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  1506. * lengths instead of fixing only the wrong ones. This idea is taken
  1507. * from 'ar' written by Haruhiko Okumura.)
  1508. */
  1509. for (bits = max_length; bits != 0; bits--) {
  1510. n = s->bl_count[bits];
  1511. while (n != 0) {
  1512. m = s->heap[--h];
  1513. if (m > max_code) continue;
  1514. if (tree[m].Len != (unsigned) bits) {
  1515. s->opt_len += ((long)bits - (long)tree[m].Len)
  1516. *(long)tree[m].Freq;
  1517. tree[m].Len = (ush)bits;
  1518. }
  1519. n--;
  1520. }
  1521. }
  1522. }
  1523. local void build_tree(s, desc)
  1524. deflate_state *s;
  1525. tree_desc *desc; /* the tree descriptor */
  1526. {
  1527. ct_data *tree = desc->dyn_tree;
  1528. ct_data *stree = desc->stat_desc->static_tree;
  1529. int elems = desc->stat_desc->elems;
  1530. int n, m; /* iterate over heap elements */
  1531. int max_code = -1; /* largest code with non zero frequency */
  1532. int node = elems; /* next internal node of the tree */
  1533. int new; /* new node being created */
  1534. /* Construct the initial heap, with least frequent element in
  1535. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  1536. * heap[0] is not used.
  1537. */
  1538. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  1539. for (n = 0; n < elems; n++) {
  1540. if (tree[n].Freq != 0) {
  1541. s->heap[++(s->heap_len)] = max_code = n;
  1542. s->depth[n] = 0;
  1543. } else {
  1544. tree[n].Len = 0;
  1545. }
  1546. }
  1547. /* The pkzip format requires that at least one distance code exists,
  1548. * and that at least one bit should be sent even if there is only one
  1549. * possible code. So to avoid special checks later on we force at least
  1550. * two codes of non zero frequency.
  1551. */
  1552. while (s->heap_len < 2) {
  1553. new = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  1554. tree[new].Freq = 1;
  1555. s->depth[new] = 0;
  1556. s->opt_len--; if (stree) s->static_len -= stree[new].Len;
  1557. /* new is 0 or 1 so it does not have extra bits */
  1558. }
  1559. desc->max_code = max_code;
  1560. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  1561. * establish sub-heaps of increasing lengths:
  1562. */
  1563. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  1564. /* Construct the Huffman tree by repeatedly combining the least two
  1565. * frequent nodes.
  1566. */
  1567. do {
  1568. pqremove(s, tree, n); /* n = node of least frequency */
  1569. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  1570. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  1571. s->heap[--(s->heap_max)] = m;
  1572. /* Create a new node father of n and m */
  1573. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  1574. s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
  1575. tree[n].Dad = tree[m].Dad = (ush)node;
  1576. #ifdef DUMP_BL_TREE
  1577. if (tree == s->bl_tree) {
  1578. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  1579. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  1580. }
  1581. #endif
  1582. /* and insert the new node in the heap */
  1583. s->heap[SMALLEST] = node++;
  1584. pqdownheap(s, tree, SMALLEST);
  1585. } while (s->heap_len >= 2);
  1586. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  1587. /* At this point, the fields freq and dad are set. We can now
  1588. * generate the bit lengths.
  1589. */
  1590. gen_bitlen(s, (tree_desc *)desc);
  1591. /* The field len is now set, we can generate the bit codes */
  1592. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  1593. }
  1594. local void scan_tree (s, tree, max_code)
  1595. deflate_state *s;
  1596. ct_data *tree; /* the tree to be scanned */
  1597. int max_code; /* and its largest code of non zero frequency */
  1598. {
  1599. int n; /* iterates over all tree elements */
  1600. int prevlen = -1; /* last emitted length */
  1601. int curlen; /* length of current code */
  1602. int nextlen = tree[0].Len; /* length of next code */
  1603. int count = 0; /* repeat count of the current code */
  1604. int max_count = 7; /* max repeat count */
  1605. int min_count = 4; /* min repeat count */
  1606. if (nextlen == 0) max_count = 138, min_count = 3;
  1607. tree[max_code+1].Len = (ush)0xffff; /* guard */
  1608. for (n = 0; n <= max_code; n++) {
  1609. curlen = nextlen; nextlen = tree[n+1].Len;
  1610. if (++count < max_count && curlen == nextlen) {
  1611. continue;
  1612. } else if (count < min_count) {
  1613. s->bl_tree[curlen].Freq += count;
  1614. } else if (curlen != 0) {
  1615. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  1616. s->bl_tree[REP_3_6].Freq++;
  1617. } else if (count <= 10) {
  1618. s->bl_tree[REPZ_3_10].Freq++;
  1619. } else {
  1620. s->bl_tree[REPZ_11_138].Freq++;
  1621. }
  1622. count = 0; prevlen = curlen;
  1623. if (nextlen == 0) {
  1624. max_count = 138, min_count = 3;
  1625. } else if (curlen == nextlen) {
  1626. max_count = 6, min_count = 3;
  1627. } else {
  1628. max_count = 7, min_count = 4;
  1629. }
  1630. }
  1631. }
  1632. local int build_bl_tree(s)
  1633. deflate_state *s;
  1634. {
  1635. int max_blindex; /* index of last bit length code of non zero freq */
  1636. /* Determine the bit length frequencies for literal and distance trees */
  1637. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  1638. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  1639. /* Build the bit length tree: */
  1640. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  1641. /* opt_len now includes the length of the tree representations, except
  1642. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  1643. */
  1644. /* Determine the number of bit length codes to send. The pkzip format
  1645. * requires that at least 4 bit length codes be sent. (appnote.txt says
  1646. * 3 but the actual value used is 4.)
  1647. */
  1648. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  1649. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  1650. }
  1651. /* Update opt_len to include the bit length tree and counts */
  1652. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  1653. return max_blindex;
  1654. }
  1655. local void send_bits(s, value, length)
  1656. deflate_state *s;
  1657. int value; /* value to send */
  1658. int length; /* number of bits */
  1659. {
  1660. #ifdef DEBUG
  1661. Assert(length > 0 && length <= 15, "invalid length");
  1662. s->bits_sent += (ulg)length;
  1663. #endif
  1664. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  1665. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  1666. * unused bits in value.
  1667. */
  1668. if (s->bi_valid > (int)Buf_size - length) {
  1669. s->bi_buf |= (value << s->bi_valid);
  1670. put_short(s, s->bi_buf);
  1671. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  1672. s->bi_valid += length - Buf_size;
  1673. } else {
  1674. s->bi_buf |= value << s->bi_valid;
  1675. s->bi_valid += length;
  1676. }
  1677. }
  1678. local void bi_windup(s)
  1679. deflate_state *s;
  1680. {
  1681. if (s->bi_valid > 8) {
  1682. put_short(s, s->bi_buf);
  1683. } else if (s->bi_valid > 0) {
  1684. put_byte(s, (Byte)s->bi_buf);
  1685. }
  1686. s->bi_buf = 0;
  1687. s->bi_valid = 0;
  1688. #ifdef DEBUG
  1689. s->bits_sent = (s->bits_sent+7) & ~7;
  1690. #endif
  1691. }
  1692. local void copy_block(s, buf, len, header)
  1693. deflate_state *s;
  1694. char *buf; /* the input data */
  1695. unsigned len; /* its length */
  1696. int header; /* true if block header must be written */
  1697. {
  1698. bi_windup(s); /* align on byte boundary */
  1699. if (header) {
  1700. put_short(s, (ush)len);
  1701. put_short(s, (ush)~len);
  1702. #ifdef DEBUG
  1703. s->bits_sent += 2*16;
  1704. #endif
  1705. }
  1706. #ifdef DEBUG
  1707. s->bits_sent += (ulg)len<<3;
  1708. #endif
  1709. while (len--) {
  1710. put_byte(s, *buf++);
  1711. }
  1712. }
  1713. local void compress_block(s, ltree, dtree)
  1714. deflate_state *s;
  1715. ct_data *ltree; /* literal tree */
  1716. ct_data *dtree; /* distance tree */
  1717. {
  1718. unsigned dist; /* distance of matched string */
  1719. int lc; /* match length or unmatched char (if dist == 0) */
  1720. unsigned lx = 0; /* running index in l_buf */
  1721. unsigned code; /* the code to send */
  1722. int extra; /* number of extra bits to send */
  1723. if (s->last_lit != 0) do {
  1724. dist = s->d_buf[lx];
  1725. lc = s->l_buf[lx++];
  1726. if (dist == 0) {
  1727. send_code(s, lc, ltree); /* send a literal byte */
  1728. } else {
  1729. /* Here, lc is the match length - MIN_MATCH */
  1730. code = length_code[lc];
  1731. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  1732. extra = extra_lbits[code];
  1733. if (extra != 0) {
  1734. lc -= base_length[code];
  1735. send_bits(s, lc, extra); /* send the extra length bits */
  1736. }
  1737. dist--; /* dist is now the match distance - 1 */
  1738. code = d_code(dist);
  1739. Assert (code < D_CODES, "bad d_code");
  1740. send_code(s, code, dtree); /* send the distance code */
  1741. extra = extra_dbits[code];
  1742. if (extra != 0) {
  1743. dist -= base_dist[code];
  1744. send_bits(s, dist, extra); /* send the extra distance bits */
  1745. }
  1746. } /* literal or match pair ? */
  1747. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  1748. Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
  1749. } while (lx < s->last_lit);
  1750. send_code(s, END_BLOCK, ltree);
  1751. }
  1752. local void send_tree (s, tree, max_code)
  1753. deflate_state *s;
  1754. ct_data *tree; /* the tree to be scanned */
  1755. int max_code; /* and its largest code of non zero frequency */
  1756. {
  1757. int n; /* iterates over all tree elements */
  1758. int prevlen = -1; /* last emitted length */
  1759. int curlen; /* length of current code */
  1760. int nextlen = tree[0].Len; /* length of next code */
  1761. int count = 0; /* repeat count of the current code */
  1762. int max_count = 7; /* max repeat count */
  1763. int min_count = 4; /* min repeat count */
  1764. /* tree[max_code+1].Len = -1; */ /* guard already set */
  1765. if (nextlen == 0) max_count = 138, min_count = 3;
  1766. for (n = 0; n <= max_code; n++) {
  1767. curlen = nextlen; nextlen = tree[n+1].Len;
  1768. if (++count < max_count && curlen == nextlen) {
  1769. continue;
  1770. } else if (count < min_count) {
  1771. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  1772. } else if (curlen != 0) {
  1773. if (curlen != prevlen) {
  1774. send_code(s, curlen, s->bl_tree); count--;
  1775. }
  1776. Assert(count >= 3 && count <= 6, " 3_6?");
  1777. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  1778. } else if (count <= 10) {
  1779. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  1780. } else {
  1781. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  1782. }
  1783. count = 0; prevlen = curlen;
  1784. if (nextlen == 0) {
  1785. max_count = 138, min_count = 3;
  1786. } else if (curlen == nextlen) {
  1787. max_count = 6, min_count = 3;
  1788. } else {
  1789. max_count = 7, min_count = 4;
  1790. }
  1791. }
  1792. }
  1793. local void send_all_trees(s, lcodes, dcodes, blcodes)
  1794. deflate_state *s;
  1795. int lcodes, dcodes, blcodes; /* number of codes for each tree */
  1796. {
  1797. int rank; /* index in bl_order */
  1798. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  1799. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  1800. "too many codes");
  1801. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  1802. send_bits(s, dcodes-1, 5);
  1803. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  1804. for (rank = 0; rank < blcodes; rank++) {
  1805. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  1806. }
  1807. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  1808. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  1809. }
  1810. ulg ct_flush_block(s, buf, stored_len, eof)
  1811. deflate_state *s;
  1812. char *buf; /* input block, or NULL if too old */
  1813. ulg stored_len; /* length of input block */
  1814. int eof; /* true if this is the last block for a file */
  1815. {
  1816. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  1817. int max_blindex; /* index of last bit length code of non zero freq */
  1818. /* Check if the file is ascii or binary */
  1819. if (s->data_type == UNKNOWN) set_data_type(s);
  1820. /* Construct the literal and distance trees */
  1821. build_tree(s, (tree_desc *)(&(s->l_desc)));
  1822. build_tree(s, (tree_desc *)(&(s->d_desc)));
  1823. /* At this point, opt_len and static_len are the total bit lengths of
  1824. * the compressed block data, excluding the tree representations.
  1825. */
  1826. /* Build the bit length tree for the above two trees, and get the index
  1827. * in bl_order of the last bit length code to send.
  1828. */
  1829. max_blindex = build_bl_tree(s);
  1830. /* Determine the best encoding. Compute first the block length in bytes */
  1831. opt_lenb = (s->opt_len+3+7)>>3;
  1832. static_lenb = (s->static_len+3+7)>>3;
  1833. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  1834. /* If compression failed and this is the first and last block,
  1835. * and if the .zip file can be seeked (to rewrite the local header),
  1836. * the whole file is transformed into a stored file:
  1837. */
  1838. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  1839. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1840. * Otherwise we can't have processed more than WSIZE input bytes since
  1841. * the last block flush, because compression would have been
  1842. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1843. * transform a block into a stored block.
  1844. */
  1845. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  1846. s->compressed_len = (s->compressed_len + 3 + 7) & ~7L;
  1847. s->compressed_len += (stored_len + 4) << 3;
  1848. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  1849. } else if (static_lenb == opt_lenb) {
  1850. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  1851. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  1852. s->compressed_len += 3 + s->static_len;
  1853. } else {
  1854. send_bits(s, (DYN_TREES<<1)+eof, 3);
  1855. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  1856. max_blindex+1);
  1857. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  1858. s->compressed_len += 3 + s->opt_len;
  1859. }
  1860. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  1861. init_block(s);
  1862. if (eof) {
  1863. bi_windup(s);
  1864. s->compressed_len += 7; /* align on byte boundary */
  1865. }
  1866. return s->compressed_len >> 3;
  1867. }
  1868. local int deflate_fast(s, flush)
  1869. deflate_state *s;
  1870. int flush;
  1871. {
  1872. IPos hash_head; /* head of the hash chain */
  1873. int bflush; /* set if current block must be flushed */
  1874. s->prev_length = MIN_MATCH-1;
  1875. for (;;) {
  1876. /* Make sure that we always have enough lookahead, except
  1877. * at the end of the input file. We need MAX_MATCH bytes
  1878. * for the next match, plus MIN_MATCH bytes to insert the
  1879. * string following the next match.
  1880. */
  1881. if (s->lookahead < MIN_LOOKAHEAD) {
  1882. fill_window(s);
  1883. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  1884. if (s->lookahead == 0) break; /* flush the current block */
  1885. }
  1886. /* Insert the string window[strstart .. strstart+2] in the
  1887. * dictionary, and set hash_head to the head of the hash chain:
  1888. */
  1889. INSERT_STRING(s, s->strstart, hash_head);
  1890. /* Find the longest match, discarding those <= prev_length.
  1891. * At this point we have always match_length < MIN_MATCH
  1892. */
  1893. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1894. /* To simplify the code, we prevent matches with the string
  1895. * of window index 0 (in particular we have to avoid a match
  1896. * of the string with itself at the start of the input file).
  1897. */
  1898. if (s->strategy != Z_HUFFMAN_ONLY) {
  1899. s->match_length = longest_match (s, hash_head);
  1900. }
  1901. /* longest_match() sets match_start */
  1902. if (s->match_length > s->lookahead) s->match_length = s->lookahead;
  1903. }
  1904. if (s->match_length >= MIN_MATCH) {
  1905. check_match(s, s->strstart, s->match_start, s->match_length);
  1906. bflush = ct_tally(s, s->strstart - s->match_start,
  1907. s->match_length - MIN_MATCH);
  1908. s->lookahead -= s->match_length;
  1909. /* Insert new strings in the hash table only if the match length
  1910. * is not too large. This saves time but degrades compression.
  1911. */
  1912. if (s->match_length <= s->max_insert_length) {
  1913. s->match_length--; /* string at strstart already in hash table */
  1914. do {
  1915. s->strstart++;
  1916. INSERT_STRING(s, s->strstart, hash_head);
  1917. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1918. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  1919. * these bytes are garbage, but it does not matter since
  1920. * the next lookahead bytes will be emitted as literals.
  1921. */
  1922. } while (--s->match_length != 0);
  1923. s->strstart++;
  1924. } else {
  1925. s->strstart += s->match_length;
  1926. s->match_length = 0;
  1927. s->ins_h = s->window[s->strstart];
  1928. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1929. #if MIN_MATCH != 3
  1930. Call UPDATE_HASH() MIN_MATCH-3 more times
  1931. #endif
  1932. }
  1933. } else {
  1934. /* No match, output a literal byte */
  1935. bflush = ct_tally (s, 0, s->window[s->strstart]);
  1936. s->lookahead--;
  1937. s->strstart++;
  1938. }
  1939. if (bflush) FLUSH_BLOCK(s, 0);
  1940. }
  1941. FLUSH_BLOCK(s, flush == Z_FINISH);
  1942. return 0; /* normal exit */
  1943. }
  1944. local int deflate_slow(s, flush)
  1945. deflate_state *s;
  1946. int flush;
  1947. {
  1948. IPos hash_head; /* head of hash chain */
  1949. int bflush; /* set if current block must be flushed */
  1950. /* Process the input block. */
  1951. for (;;) {
  1952. /* Make sure that we always have enough lookahead, except
  1953. * at the end of the input file. We need MAX_MATCH bytes
  1954. * for the next match, plus MIN_MATCH bytes to insert the
  1955. * string following the next match.
  1956. */
  1957. if (s->lookahead < MIN_LOOKAHEAD) {
  1958. fill_window(s);
  1959. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  1960. if (s->lookahead == 0) break; /* flush the current block */
  1961. }
  1962. /* Insert the string window[strstart .. strstart+2] in the
  1963. * dictionary, and set hash_head to the head of the hash chain:
  1964. */
  1965. INSERT_STRING(s, s->strstart, hash_head);
  1966. /* Find the longest match, discarding those <= prev_length.
  1967. */
  1968. s->prev_length = s->match_length, s->prev_match = s->match_start;
  1969. s->match_length = MIN_MATCH-1;
  1970. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1971. s->strstart - hash_head <= MAX_DIST(s)) {
  1972. /* To simplify the code, we prevent matches with the string
  1973. * of window index 0 (in particular we have to avoid a match
  1974. * of the string with itself at the start of the input file).
  1975. */
  1976. if (s->strategy != Z_HUFFMAN_ONLY) {
  1977. s->match_length = longest_match (s, hash_head);
  1978. }
  1979. /* longest_match() sets match_start */
  1980. if (s->match_length > s->lookahead) s->match_length = s->lookahead;
  1981. if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
  1982. (s->match_length == MIN_MATCH &&
  1983. s->strstart - s->match_start > TOO_FAR))) {
  1984. /* If prev_match is also MIN_MATCH, match_start is garbage
  1985. * but we will ignore the current match anyway.
  1986. */
  1987. s->match_length = MIN_MATCH-1;
  1988. }
  1989. }
  1990. /* If there was a match at the previous step and the current
  1991. * match is not better, output the previous match:
  1992. */
  1993. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1994. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1995. bflush = ct_tally(s, s->strstart -1 - s->prev_match,
  1996. s->prev_length - MIN_MATCH);
  1997. /* Insert in hash table all strings up to the end of the match.
  1998. * strstart-1 and strstart are already inserted.
  1999. */
  2000. s->lookahead -= s->prev_length-1;
  2001. s->prev_length -= 2;
  2002. do {
  2003. s->strstart++;
  2004. INSERT_STRING(s, s->strstart, hash_head);
  2005. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  2006. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  2007. * these bytes are garbage, but it does not matter since the
  2008. * next lookahead bytes will always be emitted as literals.
  2009. */
  2010. } while (--s->prev_length != 0);
  2011. s->match_available = 0;
  2012. s->match_length = MIN_MATCH-1;
  2013. s->strstart++;
  2014. if (bflush) FLUSH_BLOCK(s, 0);
  2015. } else if (s->match_available) {
  2016. /* If there was no match at the previous position, output a
  2017. * single literal. If there was a match but the current match
  2018. * is longer, truncate the previous match to a single literal.
  2019. */
  2020. if (ct_tally (s, 0, s->window[s->strstart-1])) {
  2021. FLUSH_BLOCK_ONLY(s, 0);
  2022. }
  2023. s->strstart++;
  2024. s->lookahead--;
  2025. if (s->strm->avail_out == 0) return 1;
  2026. } else {
  2027. /* There is no previous match to compare with, wait for
  2028. * the next step to decide.
  2029. */
  2030. s->match_available = 1;
  2031. s->strstart++;
  2032. s->lookahead--;
  2033. }
  2034. }
  2035. if (s->match_available) ct_tally (s, 0, s->window[s->strstart-1]);
  2036. FLUSH_BLOCK(s, flush == Z_FINISH);
  2037. return 0;
  2038. }
  2039. local int deflate (strm, flush)
  2040. z_stream *strm;
  2041. int flush;
  2042. {
  2043. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  2044. if (strm->next_out == Z_NULL || strm->next_in == Z_NULL) {
  2045. ERR_RETURN(strm, Z_STREAM_ERROR);
  2046. }
  2047. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  2048. strm->state->strm = strm; /* just in case */
  2049. /* Write the zlib header */
  2050. if (strm->state->status == INIT_STATE) {
  2051. uInt header = (DEFLATED + ((strm->state->w_bits-8)<<4)) << 8;
  2052. uInt level_flags = (strm->state->level-1) >> 1;
  2053. if (level_flags > 3) level_flags = 3;
  2054. header |= (level_flags << 6);
  2055. header += 31 - (header % 31);
  2056. strm->state->status = BUSY_STATE;
  2057. putShortMSB(strm->state, header);
  2058. }
  2059. /* Flush as much pending output as possible */
  2060. if (strm->state->pending != 0) {
  2061. flush_pending(strm);
  2062. if (strm->avail_out == 0) return Z_OK;
  2063. }
  2064. /* User must not provide more input after the first FINISH: */
  2065. if (strm->state->status == FINISH_STATE && strm->avail_in != 0) {
  2066. ERR_RETURN(strm, Z_BUF_ERROR);
  2067. }
  2068. /* Start a new block or continue the current one.
  2069. */
  2070. if (strm->avail_in != 0 ||
  2071. (flush == Z_FINISH && strm->state->status != FINISH_STATE)) {
  2072. if (flush == Z_FINISH) {
  2073. strm->state->status = FINISH_STATE;
  2074. }
  2075. if (strm->state->level <= 3) {
  2076. if (deflate_fast(strm->state, flush)) return Z_OK;
  2077. } else {
  2078. if (deflate_slow(strm->state, flush)) return Z_OK;
  2079. }
  2080. }
  2081. Assert(strm->avail_out > 0, "bug2");
  2082. if (flush != Z_FINISH) return Z_OK;
  2083. if (strm->state->noheader) return Z_STREAM_END;
  2084. /* Write the zlib trailer (adler32) */
  2085. putShortMSB(strm->state, (uInt)(strm->state->adler >> 16));
  2086. putShortMSB(strm->state, (uInt)(strm->state->adler & 0xffff));
  2087. flush_pending(strm);
  2088. /* If avail_out is zero, the application will call deflate again
  2089. * to flush the rest.
  2090. */
  2091. strm->state->noheader = 1; /* write the trailer only once! */
  2092. return strm->state->pending != 0 ? Z_OK : Z_STREAM_END;
  2093. }
  2094. local int gzflush (file, flush)
  2095. gzFile file;
  2096. int flush;
  2097. {
  2098. uInt len;
  2099. int done = 0;
  2100. gz_stream *s = (gz_stream*)file;
  2101. if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  2102. s->stream.avail_in = 0; /* should be zero already anyway */
  2103. for (;;) {
  2104. len = Z_BUFSIZE - s->stream.avail_out;
  2105. if (len != 0) {
  2106. if (fwrite(s->outbuf, 1, len, s->file) != len) {
  2107. s->z_err = Z_ERRNO;
  2108. return Z_ERRNO;
  2109. }
  2110. s->stream.next_out = s->outbuf;
  2111. s->stream.avail_out = Z_BUFSIZE;
  2112. }
  2113. if (done) break;
  2114. s->z_err = deflate(&(s->stream), flush);
  2115. /* deflate has finished flushing only when it hasn't used up
  2116. * all the available space in the output buffer:
  2117. */
  2118. done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
  2119. if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
  2120. }
  2121. return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
  2122. }
  2123. local gzFile gz_open (path, mode, fd)
  2124. char *path;
  2125. char *mode;
  2126. int fd;
  2127. {
  2128. int err;
  2129. char *p = mode;
  2130. gz_stream *s = (gz_stream *)ALLOC(sizeof(gz_stream));
  2131. if (!s) return Z_NULL;
  2132. s->stream.zalloc = (alloc_func)0;
  2133. s->stream.zfree = (free_func)0;
  2134. s->stream.next_in = s->inbuf = Z_NULL;
  2135. s->stream.next_out = s->outbuf = Z_NULL;
  2136. s->stream.avail_in = s->stream.avail_out = 0;
  2137. s->file = NULL;
  2138. s->z_err = Z_OK;
  2139. s->z_eof = 0;
  2140. s->crc = crc32(0L, Z_NULL, 0);
  2141. s->msg = NULL;
  2142. s->transparent = 0;
  2143. s->path = (char*)ALLOC(strlen(path)+1);
  2144. if (s->path == NULL) {
  2145. return destroy(s), (gzFile)Z_NULL;
  2146. }
  2147. strcpy(s->path, path); /* do this early for debugging */
  2148. s->mode = '\0';
  2149. do {
  2150. if (*p == 'r') s->mode = 'r';
  2151. if (*p == 'w') s->mode = 'w';
  2152. } while (*p++);
  2153. if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
  2154. if (s->mode == 'w') {
  2155. err = deflateInit2(&(s->stream), Z_BEST_COMPRESSION,
  2156. DEFLATED, -WBITS, MEM_LEVEL, 0);
  2157. /* windowBits is passed < 0 to suppress zlib header */
  2158. s->stream.next_out = s->outbuf = ALLOC(Z_BUFSIZE);
  2159. if (err != Z_OK || s->outbuf == Z_NULL) {
  2160. return destroy(s), (gzFile)Z_NULL;
  2161. }
  2162. } else {
  2163. err = inflateInit2(&(s->stream), -WBITS);
  2164. s->stream.next_in = s->inbuf = ALLOC(Z_BUFSIZE);
  2165. if (err != Z_OK || s->inbuf == Z_NULL) {
  2166. return destroy(s), (gzFile)Z_NULL;
  2167. }
  2168. }
  2169. s->stream.avail_out = Z_BUFSIZE;
  2170. errno = 0;
  2171. s->file = fd < 0 ? fopen(path, mode) : fdopen(fd, mode);
  2172. if (s->file == NULL) {
  2173. return destroy(s), (gzFile)Z_NULL;
  2174. }
  2175. if (s->mode == 'w') {
  2176. /* Write a very simple .gz header:
  2177. */
  2178. fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", GZ_MAGIC_1, GZ_MAGIC_2,
  2179. DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
  2180. } else {
  2181. /* Check and skip the header:
  2182. */
  2183. Byte c1 = 0, c2 = 0;
  2184. Byte method = 0;
  2185. Byte flags = 0;
  2186. Byte xflags = 0;
  2187. Byte time[4];
  2188. Byte osCode;
  2189. int c;
  2190. s->stream.avail_in = fread(s->inbuf, 1, 2, s->file);
  2191. if (s->stream.avail_in != 2 || s->inbuf[0] != GZ_MAGIC_1
  2192. || s->inbuf[1] != GZ_MAGIC_2) {
  2193. s->transparent = 1;
  2194. return (gzFile)s;
  2195. }
  2196. s->stream.avail_in = 0;
  2197. err = fscanf(s->file,"%c%c%4c%c%c", &method, &flags, time, &xflags, &osCode);
  2198. if (method != DEFLATED || feof(s->file) || (flags & RESERVED) != 0) {
  2199. s->z_err = Z_DATA_ERROR;
  2200. return (gzFile)s;
  2201. }
  2202. if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
  2203. long len;
  2204. err = fscanf(s->file, "%c%c", &c1, &c2);
  2205. len = c1 + ((long)c2<<8);
  2206. fseek(s->file, len, SEEK_CUR);
  2207. }
  2208. if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
  2209. while ((c = getc(s->file)) != 0 && c != EOF) ;
  2210. }
  2211. if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
  2212. while ((c = getc(s->file)) != 0 && c != EOF) ;
  2213. }
  2214. if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
  2215. err = fscanf(s->file, "%c%c", &c1, &c2);
  2216. }
  2217. if (feof(s->file)) {
  2218. s->z_err = Z_DATA_ERROR;
  2219. }
  2220. }
  2221. return (gzFile)s;
  2222. }
  2223. local gzFile gzopen (path, mode)
  2224. char *path;
  2225. char *mode;
  2226. {
  2227. return gz_open (path, mode, -1);
  2228. }
  2229. local int gzwrite (file, buf, len)
  2230. gzFile file;
  2231. voidp buf;
  2232. unsigned len;
  2233. {
  2234. gz_stream *s = (gz_stream*)file;
  2235. if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  2236. s->stream.next_in = buf;
  2237. s->stream.avail_in = len;
  2238. while (s->stream.avail_in != 0) {
  2239. if (s->stream.avail_out == 0) {
  2240. s->stream.next_out = s->outbuf;
  2241. if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
  2242. s->z_err = Z_ERRNO;
  2243. break;
  2244. }
  2245. s->stream.avail_out = Z_BUFSIZE;
  2246. }
  2247. s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
  2248. if (s->z_err != Z_OK) break;
  2249. }
  2250. s->crc = crc32(s->crc, buf, len);
  2251. return len - s->stream.avail_in;
  2252. }
  2253. local int gzclose (file)
  2254. gzFile file;
  2255. {
  2256. uInt n;
  2257. int err;
  2258. gz_stream *s = (gz_stream*)file;
  2259. if (s == NULL) return Z_STREAM_ERROR;
  2260. if (s->mode == 'w') {
  2261. err = gzflush (file, Z_FINISH);
  2262. if (err != Z_OK) return destroy((gz_stream *)file);
  2263. putLong (s->file, s->crc);
  2264. putLong (s->file, s->stream.total_in);
  2265. } else if (s->mode == 'r' && s->z_err == Z_STREAM_END) {
  2266. /* slide CRC and original size if they are at the end of inbuf */
  2267. if ((n = s->stream.avail_in) < 8 && !s->z_eof) {
  2268. Byte *p = s->inbuf;
  2269. Byte *q = s->stream.next_in;
  2270. while (n--) { *p++ = *q++; };
  2271. n = s->stream.avail_in;
  2272. n += fread(p, 1, 8, s->file);
  2273. s->stream.next_in = s->inbuf;
  2274. }
  2275. /* check CRC and original size */
  2276. if (n < 8 ||
  2277. getLong(s->stream.next_in) != s->crc ||
  2278. getLong(s->stream.next_in + 4) != s->stream.total_out) {
  2279. s->z_err = Z_DATA_ERROR;
  2280. }
  2281. }
  2282. return destroy((gz_stream *)file);
  2283. }
  2284. /* ========================================================================= */
  2285. static int wm_tool_printf(const char *format, ...)
  2286. {
  2287. int ret;
  2288. va_list ap;
  2289. va_start(ap, format);
  2290. ret = vprintf(format, ap);
  2291. va_end(ap);
  2292. fflush(stdout);
  2293. return ret;
  2294. }
  2295. static unsigned long long wm_tool_crc32_reflect(unsigned long long ref, unsigned char ch)
  2296. {
  2297. int i;
  2298. unsigned long long value = 0;
  2299. for ( i = 1; i < ( ch + 1 ); i++ )
  2300. {
  2301. if( ref & 1 )
  2302. value |= 1 << ( ch - i );
  2303. ref >>= 1;
  2304. }
  2305. return value;
  2306. }
  2307. static unsigned int wm_tool_crc32(unsigned int crc, unsigned char *buffer, int size, wm_tool_crc32_reflect_e mode)
  2308. {
  2309. int i;
  2310. unsigned char temp;
  2311. for (i = 0; i < size; i++)
  2312. {
  2313. if (mode & WM_TOOL_CRC32_REFLECT_INPUT)
  2314. {
  2315. temp = wm_tool_crc32_reflect(buffer[i], 8);
  2316. }
  2317. else
  2318. {
  2319. temp = buffer[i];
  2320. }
  2321. crc = wm_tool_crc32_tab[(crc ^ temp) & 0xff] ^ (crc >> 8);
  2322. }
  2323. return crc ;
  2324. }
  2325. static unsigned int wm_tool_get_crc32(unsigned char *buffer, int size, wm_tool_crc32_reflect_e mode)
  2326. {
  2327. wm_tool_file_crc = wm_tool_crc32(wm_tool_file_crc, buffer, size, mode);
  2328. if (mode & WM_TOOL_CRC32_REFLECT_OUTPUT)
  2329. {
  2330. wm_tool_file_crc = wm_tool_crc32_reflect(wm_tool_file_crc, 32);
  2331. }
  2332. return wm_tool_file_crc;
  2333. }
  2334. static unsigned short wm_tool_get_crc16(unsigned char *ptr, unsigned short count)
  2335. {
  2336. unsigned short crc, i;
  2337. crc = 0;
  2338. while (count--)
  2339. {
  2340. crc = crc ^ (int) *ptr++ << 8;
  2341. for (i = 0; i < 8; i++)
  2342. {
  2343. if (crc & 0x8000)
  2344. crc = crc << 1 ^ 0x1021;
  2345. else
  2346. crc = crc << 1;
  2347. }
  2348. }
  2349. return (crc & 0xFFFF);
  2350. }
  2351. static int wm_tool_char_to_hex(char ch)
  2352. {
  2353. int hex;
  2354. hex = -1;
  2355. if ((ch >= '0') && (ch <= '9'))
  2356. {
  2357. hex = ch - '0';
  2358. }
  2359. else if ((ch >= 'a') && (ch <= 'f'))
  2360. {
  2361. hex = ch - 'a' + 0xa;
  2362. }
  2363. else if ((ch >= 'A') && (ch <= 'F'))
  2364. {
  2365. hex = ch - 'A' + 0xa;
  2366. }
  2367. return hex;
  2368. }
  2369. static int wm_tool_str_to_hex_array(char *str, int cnt, unsigned char array[])
  2370. {
  2371. int hex;
  2372. unsigned char tmp;
  2373. unsigned char *des;
  2374. des = array;
  2375. while (cnt-- > 0)
  2376. {
  2377. hex = wm_tool_char_to_hex(*str++);
  2378. if (hex < 0)
  2379. {
  2380. return -1;
  2381. }
  2382. else
  2383. {
  2384. tmp = (hex << 4) & 0xf0;
  2385. }
  2386. hex = wm_tool_char_to_hex(*str++);
  2387. if (hex < 0)
  2388. {
  2389. return -1;
  2390. }
  2391. else
  2392. {
  2393. tmp = tmp | (hex & 0x0f);
  2394. }
  2395. *des++ = (unsigned char) tmp;
  2396. }
  2397. return ((*str == 0) ? 0 : -1);
  2398. }
  2399. static char *wm_tool_strcasestr(const char *str1, const char *str2)
  2400. {
  2401. char *cp = (char *) str1;
  2402. char *s1, *s2;
  2403. if (!*str2) return (char *) str1;
  2404. while (*cp) {
  2405. s1 = cp;
  2406. s2 = (char *) str2;
  2407. while (*s1 && *s2 && !(tolower((int)*s1) - tolower((int)*s2))) s1++, s2++;
  2408. if (!*s2) return cp;
  2409. cp++;
  2410. }
  2411. return NULL;
  2412. }
  2413. static int wm_tool_get_file_size(const char* filename)
  2414. {
  2415. FILE *fp = fopen(filename, "r");
  2416. if(!fp) return -1;
  2417. fseek(fp,0L,SEEK_END);
  2418. int size = ftell(fp);
  2419. fclose(fp);
  2420. return size;
  2421. }
  2422. static char *wm_tool_get_name(const char *name)
  2423. {
  2424. static char sz_name[WM_TOOL_PATH_MAX] = {0};
  2425. char *p = (char *)name;
  2426. char *q = (char *)name;
  2427. do
  2428. {
  2429. #ifdef __MINGW32__
  2430. p = strchr(p, '\\');
  2431. #else
  2432. p = strchr(p, '/');
  2433. #endif
  2434. if (p)
  2435. {
  2436. p++;
  2437. q = p;
  2438. }
  2439. } while (p);
  2440. strncpy(sz_name, q, WM_TOOL_PATH_MAX - 1);
  2441. #ifdef __MINGW32__
  2442. p = wm_tool_strcasestr(sz_name, ".exe");
  2443. if (p)
  2444. *p = '\0';
  2445. #endif
  2446. return sz_name;
  2447. }
  2448. static void wm_tool_print_usage(const char *name)
  2449. {
  2450. wm_tool_printf("Usage: %s [-h] [-v] [-b] [-o] [-sb] [-ct] [-it]"
  2451. " [-ua] [-ra] [-ih] [-nh] [-un] [-df] [-vs]"
  2452. " [-l] [-c] [-ws] [-ds] [-rs] [-eo] [-dl] [-sl]"
  2453. "\r\n"
  2454. "\r\n"
  2455. "WinnerMicro firmware packaging "
  2456. "and programming "
  2457. "tool\r\n\r\n"
  2458. "options:\r\n\r\n"
  2459. " -h , show usage\r\n"
  2460. " -v , show version\r\n"
  2461. "\r\n"
  2462. " -b binary , original binary file\r\n"
  2463. " -o output_name , output firmware file\r\n"
  2464. " the default is the same as the original binary file name\r\n"
  2465. " -sb second_boot , second boot file, used to generate fls file\r\n"
  2466. " -fc compress_type , whether the firmware is compressed, default is compressed\r\n"
  2467. " <0 | 1> or <uncompress | compress>\r\n"
  2468. " -it image_type , firmware image layout type, default is 0\r\n"
  2469. " <0 | 1>\r\n"
  2470. " -ua update_address , upgrade storage location (hexadecimal)\r\n"
  2471. " the default is 8090000\r\n"
  2472. " -ra run_address , runtime position (hexadecimal)\r\n"
  2473. " the default is 8002400\r\n"
  2474. " -ih image_header , image header storage location (hexadecimal)\r\n"
  2475. " the default is 8002000\r\n"
  2476. " -nh next_image_header , next image header storage location (hexadecimal)\r\n"
  2477. " the default is 0\r\n"
  2478. " -un upd_no , upd no version number (hexadecimal)\r\n"
  2479. " the default is 0\r\n"
  2480. " -df , generate debug firmware for openocd\r\n"
  2481. " -vs version_string , firmware version string, cannot exceed 16 bytes\r\n"
  2482. "\r\n"
  2483. " -l , list the local serial port\r\n"
  2484. " -c serial_name , connect a serial port\r\n"
  2485. #if defined(__APPLE__) && defined(__MACH__)
  2486. " e.g: tty.usbserial0 tty.usbserial3 tty.usbserial7\r\n"
  2487. #elif defined(__MINGW32__) || defined(__CYGWIN__)
  2488. " e.g: COM0 COM3 COM7\r\n"
  2489. #elif defined(__linux__)
  2490. " e.g: ttyUSB0 ttyUSB3 ttyUSB7\r\n"
  2491. #endif
  2492. " -ws baud_rate , set the serial port speed during normal work, default is 115200\r\n"
  2493. " <1200 - 2000000> or <1M | 2M>\r\n"
  2494. " -ds baud_rate , set the serial port speed when downloading, default is 115200\r\n"
  2495. " <115200 | 460800 | 921600 | 1000000 | 2000000> or <1M | 2M>\r\n"
  2496. " -rs reset_action , set device reset method, default is manual control\r\n"
  2497. " <none | at | rts>\r\n"
  2498. " none - manual control device reset\r\n"
  2499. " at - use the at command to control the device reset\r\n"
  2500. " rts - use the serial port rts pin to control the device reset\r\n"
  2501. " -eo erase_option , firmware area erase option\r\n"
  2502. " <all>\r\n"
  2503. " all - erase all areas\r\n"
  2504. " -dl download_firmware , firmware file to be downloaded, default download compressed image\r\n"
  2505. " -sl display_format , display the log information output from the serial port\r\n"
  2506. " <0 | 1> or <str | hex>\r\n"
  2507. " str - string mode display\r\n"
  2508. " hex - hexadecimal format\r\n"
  2509. , wm_tool_get_name(name));
  2510. return;
  2511. }
  2512. static void wm_tool_print_version(const char *name)
  2513. {
  2514. wm_tool_printf("%s %s for xt804\r\nCopyright (C) 2021 AirM2M, Inc.\r\n", wm_tool_get_name(name), wm_tool_version);
  2515. return;
  2516. }
  2517. static int wm_tool_parse_arv(int argc, char *argv[])
  2518. {
  2519. int opt;
  2520. int option_index = 0;
  2521. char *opt_string = "hvlc:b:o:";
  2522. int cnt = 0;
  2523. opterr = 1;/* show err info */
  2524. struct option long_options[] = {
  2525. {"dl", required_argument, NULL, 'd'},
  2526. {"ws", required_argument, NULL, 'w'},
  2527. {"ds", required_argument, NULL, 's'},
  2528. {"sb", required_argument, NULL, 'S'},
  2529. {"it", required_argument, NULL, 'i'},
  2530. {"fc", required_argument, NULL, 'C'},
  2531. {"ua", required_argument, NULL, 'u'},
  2532. {"ra", required_argument, NULL, 'r'},
  2533. {"ih", required_argument, NULL, 'H'},
  2534. {"nh", required_argument, NULL, 'n'},
  2535. {"un", required_argument, NULL, 'U'},
  2536. {"df", no_argument, NULL, 'D'},
  2537. {"vs", required_argument, NULL, 'V'},
  2538. {"rs", required_argument, NULL, 'a'},
  2539. {"eo", required_argument, NULL, 'e'},
  2540. {"sl", required_argument, NULL, 'g'},
  2541. {0, 0, NULL, 0}
  2542. };
  2543. while ( (opt = getopt_long_only(argc, argv, opt_string, long_options, &option_index)) != -1)
  2544. {
  2545. WM_TOOL_DBG_PRINT("%c-%s\r\n", opt, optarg);
  2546. switch (opt)
  2547. {
  2548. case '?':
  2549. case 'h':
  2550. {
  2551. wm_tool_show_usage = 1;
  2552. break;
  2553. }
  2554. case 'v':
  2555. {
  2556. wm_tool_show_ver = 1;
  2557. break;
  2558. }
  2559. case 'l':
  2560. {
  2561. wm_tool_list_com = 1;
  2562. break;
  2563. }
  2564. case 'c':
  2565. {
  2566. #if defined(__MINGW32__)
  2567. strcpy(wm_tool_serial_path, optarg);
  2568. #elif defined(__CYGWIN__)
  2569. sprintf(wm_tool_serial_path, "/dev/ttyS%d", atoi(optarg + strlen("COM")) - 1);
  2570. #else
  2571. sprintf(wm_tool_serial_path, "/dev/%s", optarg);
  2572. #endif
  2573. break;
  2574. }
  2575. case 'w':
  2576. {
  2577. if ('M' == optarg[1])
  2578. wm_tool_normal_serial_rate = (optarg[0] - 0x30) * 1000000;
  2579. else
  2580. wm_tool_normal_serial_rate = strtol(optarg, NULL, 10);
  2581. break;
  2582. }
  2583. case 's':
  2584. {
  2585. if ('M' == optarg[1])
  2586. wm_tool_download_serial_rate = (optarg[0] - 0x30) * 1000000;
  2587. else
  2588. wm_tool_download_serial_rate = strtol(optarg, NULL, 10);
  2589. break;
  2590. }
  2591. case 'a':
  2592. {
  2593. if (0 == strncmp(optarg, "none", strlen("none")))
  2594. wm_tool_dl_action = WM_TOOL_DL_ACTION_NONE;
  2595. else if (0 == strncmp(optarg, "at", strlen("at")))
  2596. wm_tool_dl_action = WM_TOOL_DL_ACTION_AT;
  2597. else if (0 == strncmp(optarg, "rts", strlen("rts")))
  2598. wm_tool_dl_action = WM_TOOL_DL_ACTION_RTS;
  2599. else
  2600. wm_tool_show_usage = 1;
  2601. break;
  2602. }
  2603. case 'e':
  2604. {
  2605. if (0 == strncmp(optarg, "all", strlen("all")))
  2606. wm_tool_dl_erase = WM_TOOL_DL_ERASE_ALL;
  2607. else
  2608. wm_tool_show_usage = 1;
  2609. break;
  2610. }
  2611. case 'd':
  2612. {
  2613. wm_tool_download_image = strdup(optarg);
  2614. if (wm_tool_strcasestr(wm_tool_download_image, ".fls"))
  2615. wm_tool_dl_type = WM_TOOL_DL_TYPE_FLS;
  2616. break;
  2617. }
  2618. case 'o':
  2619. {
  2620. wm_tool_output_image = strdup(optarg);
  2621. break;
  2622. }
  2623. case 'b':
  2624. {
  2625. wm_tool_input_binary = strdup(optarg);
  2626. break;
  2627. }
  2628. case 'S':
  2629. {
  2630. wm_tool_secboot_image = strdup(optarg);
  2631. break;
  2632. }
  2633. case 'i':
  2634. {
  2635. #if 0
  2636. if ('0' == optarg[0])
  2637. wm_tool_image_type = WM_TOOL_LAYOUT_TYPE_1M;
  2638. else if ('3' == optarg[0])
  2639. wm_tool_image_type = WM_TOOL_LAYOUT_TYPE_2M;
  2640. else if (0 == strncmp(optarg, "1M", strlen("1M")))
  2641. wm_tool_image_type = WM_TOOL_LAYOUT_TYPE_1M;
  2642. else if (0 == strncmp(optarg, "2M", strlen("2M")))
  2643. wm_tool_image_type = WM_TOOL_LAYOUT_TYPE_2M;
  2644. else
  2645. #endif
  2646. {
  2647. if (isdigit((int)optarg[0]))
  2648. wm_tool_image_type = atoi(optarg);//optarg[0] - 0x30;
  2649. else
  2650. wm_tool_show_usage = 1;
  2651. }
  2652. break;
  2653. }
  2654. case 'C':
  2655. {
  2656. if ('0' == optarg[0])
  2657. wm_tool_zip_type = WM_TOOL_ZIP_TYPE_UNCOMPRESS;
  2658. else if ('1' == optarg[0])
  2659. wm_tool_zip_type = WM_TOOL_ZIP_TYPE_COMPRESS;
  2660. else if (0 == strncmp(optarg, "compress", strlen("compress")))
  2661. wm_tool_zip_type = WM_TOOL_ZIP_TYPE_COMPRESS;
  2662. else if (0 == strncmp(optarg, "uncompress", strlen("uncompress")))
  2663. wm_tool_zip_type = WM_TOOL_ZIP_TYPE_UNCOMPRESS;
  2664. else
  2665. wm_tool_show_usage = 1;
  2666. break;
  2667. }
  2668. case 'u':
  2669. {
  2670. wm_tool_upd_addr = strtol(optarg, NULL, 16);
  2671. break;
  2672. }
  2673. case 'r':
  2674. {
  2675. wm_tool_run_addr = strtol(optarg, NULL, 16);
  2676. break;
  2677. }
  2678. case 'D':
  2679. {
  2680. wm_tool_is_debug = 1;
  2681. break;
  2682. }
  2683. case 'V':
  2684. {
  2685. strncpy(wm_tool_image_version, optarg, WM_TOOL_IMAGE_VERSION_LEN);
  2686. wm_tool_image_version[WM_TOOL_IMAGE_VERSION_LEN - 1] = '\0';
  2687. break;
  2688. }
  2689. case 'g':
  2690. {
  2691. if ('0' == optarg[0])
  2692. wm_tool_show_log_type = WM_TOOL_SHOW_LOG_STR;
  2693. else if ('1' == optarg[0])
  2694. wm_tool_show_log_type = WM_TOOL_SHOW_LOG_HEX;
  2695. else if (0 == strncmp(optarg, "str", strlen("str")))
  2696. wm_tool_show_log_type = WM_TOOL_SHOW_LOG_STR;
  2697. else if (0 == strncmp(optarg, "hex", strlen("hex")))
  2698. wm_tool_show_log_type = WM_TOOL_SHOW_LOG_HEX;
  2699. else
  2700. wm_tool_show_usage = 1;
  2701. break;
  2702. break;
  2703. }
  2704. case 'H':
  2705. {
  2706. wm_tool_image_header = strtol(optarg, NULL, 16);
  2707. break;
  2708. }
  2709. case 'n':
  2710. {
  2711. wm_tool_next_image_header = strtol(optarg, NULL, 16);
  2712. break;
  2713. }
  2714. case 'U':
  2715. {
  2716. wm_tool_image_upd_no = strtol(optarg, NULL, 16);
  2717. break;
  2718. }
  2719. default:
  2720. {
  2721. wm_tool_show_usage = 1;
  2722. break;
  2723. }
  2724. }
  2725. cnt++;
  2726. }
  2727. return cnt;
  2728. }
  2729. static int wm_tool_pack_image(const char *outfile)
  2730. {
  2731. FILE *fpbin = NULL;
  2732. FILE *fpimg = NULL;
  2733. int readlen = 0;
  2734. int filelen = 0;
  2735. int patch = 0;
  2736. wm_tool_firmware_booter_t fbooter;
  2737. unsigned char buf[WM_TOOL_ONCE_READ_LEN + 1];
  2738. fpbin = fopen(wm_tool_input_binary, "rb");
  2739. if (NULL == fpbin)
  2740. {
  2741. wm_tool_printf("can not open input file [%s].\r\n", wm_tool_input_binary);
  2742. return -2;
  2743. }
  2744. fpimg = fopen(outfile, "wb+");
  2745. if (NULL == fpimg)
  2746. {
  2747. wm_tool_printf("open img file error: [%s].\r\n", outfile);
  2748. fclose(fpbin);
  2749. return -3;
  2750. }
  2751. /* --------deal with upgrade image's CRC begin---- */
  2752. wm_tool_file_crc = 0xFFFFFFFF;
  2753. while (!feof(fpbin))
  2754. {
  2755. memset(buf, 0, sizeof(buf));
  2756. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpbin);
  2757. if(readlen % 4 != 0)
  2758. {
  2759. patch = 4 - readlen%4;
  2760. readlen += patch;
  2761. }
  2762. filelen += readlen;
  2763. wm_tool_get_crc32((unsigned char*)buf, readlen, 0);
  2764. }
  2765. /* --------deal with upgrade image's CRC end---- */
  2766. wm_tool_src_binary_len = filelen;
  2767. wm_tool_src_binary_crc = wm_tool_file_crc;
  2768. memset(&fbooter, 0, sizeof(wm_tool_firmware_booter_t));
  2769. strcpy((char *)fbooter.ver, wm_tool_image_version);
  2770. fbooter.magic_no = WM_TOOL_IMG_HEAD_MAGIC_NO;
  2771. fbooter.run_org_checksum = wm_tool_file_crc;
  2772. fbooter.img_type = wm_tool_image_type;
  2773. fbooter.run_img_len = filelen;
  2774. fbooter.run_img_addr = wm_tool_run_addr;
  2775. fbooter.zip_type = WM_TOOL_ZIP_TYPE_UNCOMPRESS;
  2776. fbooter.img_header_addr = wm_tool_image_header;
  2777. fbooter.upgrade_img_addr = wm_tool_upd_addr;
  2778. fbooter.upd_no = wm_tool_image_upd_no;
  2779. fbooter.next_boot = wm_tool_next_image_header;
  2780. /* calculate image's header's CRC */
  2781. wm_tool_file_crc = 0xFFFFFFFF;
  2782. wm_tool_get_crc32((unsigned char *)&fbooter, sizeof(wm_tool_firmware_booter_t) - 4, 0);
  2783. fbooter.hd_checksum = wm_tool_file_crc;
  2784. /* write image's header to output file */
  2785. fwrite(&fbooter, 1, sizeof(wm_tool_firmware_booter_t), fpimg);
  2786. /* write image to output file */
  2787. fseek(fpbin, 0, SEEK_SET);
  2788. while (!feof(fpbin))
  2789. {
  2790. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpbin);
  2791. fwrite(buf, 1, readlen, fpimg);
  2792. }
  2793. /* write dummy data to pad 4byte-aligned */
  2794. if (patch > 0)
  2795. {
  2796. memset(buf, 0, patch);
  2797. fwrite(buf, 1, patch, fpimg);
  2798. }
  2799. if (fpbin)
  2800. {
  2801. fclose(fpbin);
  2802. }
  2803. if (fpimg)
  2804. {
  2805. fclose(fpimg);
  2806. }
  2807. wm_tool_printf("generate normal image completed.\r\n");
  2808. return 0;
  2809. }
  2810. static int wm_tool_pack_gz_image(const char *gzbin, const char *outfile)
  2811. {
  2812. FILE *fpbin = NULL;
  2813. FILE *fpimg = NULL;
  2814. int readlen = 0;
  2815. int filelen = 0;
  2816. int patch = 0;
  2817. wm_tool_firmware_booter_t fbooter;
  2818. unsigned char buf[WM_TOOL_ONCE_READ_LEN + 1];
  2819. fpbin = fopen(gzbin, "rb");
  2820. if (NULL == fpbin)
  2821. {
  2822. wm_tool_printf("can not open input file [%s].\r\n", gzbin);
  2823. return -2;
  2824. }
  2825. fpimg = fopen(outfile, "wb+");
  2826. if (NULL == fpimg)
  2827. {
  2828. wm_tool_printf("create img file error: [%s].\r\n", outfile);
  2829. fclose(fpbin);
  2830. return -3;
  2831. }
  2832. /* --------deal with upgrade image's CRC begin---- */
  2833. wm_tool_file_crc = 0xFFFFFFFF;
  2834. while (!feof(fpbin))
  2835. {
  2836. memset(buf, 0, sizeof(buf));
  2837. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpbin);
  2838. if(readlen % 4 != 0)
  2839. {
  2840. patch = 4 - readlen%4;
  2841. readlen += patch;
  2842. }
  2843. filelen += readlen;
  2844. wm_tool_get_crc32((unsigned char*)buf, readlen, 0);
  2845. }
  2846. /* --------deal with upgrade image's CRC end---- */
  2847. memset(&fbooter, 0, sizeof(wm_tool_firmware_booter_t));
  2848. strcpy((char *)fbooter.ver, wm_tool_image_version);
  2849. fbooter.magic_no = WM_TOOL_IMG_HEAD_MAGIC_NO;
  2850. fbooter.run_org_checksum = wm_tool_file_crc;
  2851. fbooter.img_type = wm_tool_image_type;
  2852. fbooter.run_img_len = filelen;
  2853. fbooter.run_img_addr = wm_tool_run_addr;
  2854. fbooter.zip_type = wm_tool_zip_type;
  2855. fbooter.img_header_addr = wm_tool_image_header;
  2856. fbooter.upgrade_img_addr = wm_tool_upd_addr;
  2857. fbooter.upd_no = wm_tool_image_upd_no;
  2858. fbooter.next_boot = wm_tool_next_image_header;
  2859. /* calculate image's header's CRC */
  2860. wm_tool_file_crc = 0xFFFFFFFF;
  2861. wm_tool_get_crc32((unsigned char *)&fbooter, sizeof(wm_tool_firmware_booter_t) - 4, 0);
  2862. fbooter.hd_checksum = wm_tool_file_crc;
  2863. /* write image's header to output file */
  2864. fwrite(&fbooter, 1, sizeof(wm_tool_firmware_booter_t), fpimg);
  2865. /* write image to output file */
  2866. fseek(fpbin, 0, SEEK_SET);
  2867. while (!feof(fpbin))
  2868. {
  2869. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpbin);
  2870. fwrite(buf, 1, readlen, fpimg);
  2871. }
  2872. /* write dummy data to pad 4byte-aligned */
  2873. if (patch > 0)
  2874. {
  2875. memset(buf, 0, patch);
  2876. fwrite(buf, 1, patch, fpimg);
  2877. }
  2878. if (fpbin)
  2879. {
  2880. fclose(fpbin);
  2881. }
  2882. if (fpimg)
  2883. {
  2884. fclose(fpimg);
  2885. }
  2886. wm_tool_printf("generate compressed image completed.\r\n");
  2887. return 0;
  2888. }
  2889. static int wm_tool_pack_dbg_image(const char *image, const char *outfile)
  2890. {
  2891. FILE *fpimg = NULL;
  2892. FILE *fout = NULL;
  2893. unsigned char buf[WM_TOOL_ONCE_READ_LEN + 1];
  2894. int readlen = 0;
  2895. int i;
  2896. wm_tool_firmware_booter_t fbooter;
  2897. int appimg_len = 0;
  2898. int final_len = 0;
  2899. int magic_word = 0;
  2900. fpimg = fopen(image, "rb");
  2901. if (NULL == fpimg)
  2902. {
  2903. wm_tool_printf("open img file error: [%s].\r\n", image);
  2904. return -4;
  2905. }
  2906. magic_word = 0;
  2907. readlen = fread(&magic_word, 1, 4, fpimg);
  2908. if (magic_word != WM_TOOL_IMG_HEAD_MAGIC_NO)
  2909. {
  2910. wm_tool_printf("input [%s] file magic error.\n", image);
  2911. fclose(fpimg);
  2912. return -5;
  2913. }
  2914. fout = fopen(outfile, "wb+");
  2915. if (NULL == fout)
  2916. {
  2917. wm_tool_printf("create img file error [%s].\r\n", outfile);
  2918. fclose(fpimg);
  2919. return -6;
  2920. }
  2921. appimg_len = wm_tool_get_file_size(image);
  2922. /* write 0xFF to output file */
  2923. final_len = WM_TOOL_RUN_IMG_HEADER_LEN + (appimg_len - sizeof(wm_tool_firmware_booter_t));
  2924. for (i = 0; i < (final_len /WM_TOOL_ONCE_READ_LEN); i++)
  2925. {
  2926. memset(buf, 0xff, WM_TOOL_ONCE_READ_LEN);
  2927. fwrite(buf, 1, WM_TOOL_ONCE_READ_LEN, fout);
  2928. }
  2929. memset(buf, 0xff, final_len % WM_TOOL_ONCE_READ_LEN);
  2930. fwrite(buf, 1, final_len % WM_TOOL_ONCE_READ_LEN, fout);
  2931. memset(&fbooter, 0, sizeof(wm_tool_firmware_booter_t));
  2932. /* write sec img to output file */
  2933. fseek(fpimg, 0, SEEK_SET);
  2934. readlen = fread((unsigned char *)&fbooter, 1, sizeof(wm_tool_firmware_booter_t), fpimg);
  2935. fseek(fout, 0, SEEK_SET);
  2936. fwrite(&fbooter, 1, sizeof(wm_tool_firmware_booter_t), fout);
  2937. fseek(fout, WM_TOOL_RUN_IMG_HEADER_LEN, SEEK_SET);
  2938. while (!feof(fpimg))
  2939. {
  2940. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpimg);
  2941. fwrite(buf, 1, readlen, fout);
  2942. }
  2943. if (fpimg)
  2944. {
  2945. fclose(fpimg);
  2946. }
  2947. if (fout)
  2948. {
  2949. fclose(fout);
  2950. }
  2951. wm_tool_printf("generate debug image completed.\r\n");
  2952. return 0;
  2953. }
  2954. static int wm_tool_pack_fls(const char *image, const char *outfile)
  2955. {
  2956. FILE *fpsec = NULL;
  2957. FILE *fpimg = NULL;
  2958. FILE *fout = NULL;
  2959. unsigned char buf[WM_TOOL_ONCE_READ_LEN + 1];
  2960. int readlen = 0;
  2961. int magic_word = 0;
  2962. fpsec = fopen(wm_tool_secboot_image,"rb");
  2963. if (NULL == fpsec)
  2964. {
  2965. wm_tool_printf("can not open input file [%s].\r\n", wm_tool_secboot_image);
  2966. return -2;
  2967. }
  2968. magic_word = 0;
  2969. readlen = fread(&magic_word, 1, 4, fpsec);
  2970. if (magic_word != WM_TOOL_IMG_HEAD_MAGIC_NO)
  2971. {
  2972. wm_tool_printf("input [%s] file magic error.\r\n", wm_tool_secboot_image);
  2973. fclose(fpsec);
  2974. return -3;
  2975. }
  2976. fpimg = fopen(image, "rb");
  2977. if (NULL == fpimg)
  2978. {
  2979. wm_tool_printf("open img file error [%s].\r\n", image);
  2980. fclose(fpsec);
  2981. return -4;
  2982. }
  2983. magic_word = 0;
  2984. readlen = fread(&magic_word, 1, 4, fpimg);
  2985. if (magic_word != WM_TOOL_IMG_HEAD_MAGIC_NO)
  2986. {
  2987. wm_tool_printf("input [%s] file magic error.\r\n", image);
  2988. fclose(fpsec);
  2989. fclose(fpimg);
  2990. return -5;
  2991. }
  2992. fout = fopen(outfile, "wb+");
  2993. if (NULL == fout)
  2994. {
  2995. wm_tool_printf("create img file error [%s].\r\n", outfile);
  2996. fclose(fpsec);
  2997. fclose(fpimg);
  2998. return -6;
  2999. }
  3000. fseek(fpsec, 0, SEEK_SET);
  3001. while (!feof(fpsec))
  3002. {
  3003. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpsec);
  3004. fwrite(buf, 1, readlen, fout);
  3005. }
  3006. fseek(fpimg, 0, SEEK_SET);
  3007. while (!feof(fpimg))
  3008. {
  3009. readlen = fread(buf, 1, WM_TOOL_ONCE_READ_LEN, fpimg);
  3010. fwrite(buf, 1, readlen, fout);
  3011. }
  3012. if (fpsec)
  3013. {
  3014. fclose(fpsec);
  3015. }
  3016. if (fpimg)
  3017. {
  3018. fclose(fpimg);
  3019. }
  3020. if (fout)
  3021. {
  3022. fclose(fout);
  3023. }
  3024. wm_tool_printf("generate flash file completed.\r\n");
  3025. return 0;
  3026. }
  3027. static int wm_tool_gzip_bin(const char *binary, const char *gzbin)
  3028. {
  3029. FILE *bfp;
  3030. gzFile gzfp;
  3031. int ret;
  3032. char buf[1024];
  3033. bfp = fopen(binary, "rb");
  3034. gzfp = gzopen((char *)gzbin, "wb+");
  3035. if (!bfp || !gzfp)
  3036. {
  3037. wm_tool_printf("can not gzip binary.\r\n");
  3038. return -1;
  3039. }
  3040. do {
  3041. ret = fread(buf, 1, sizeof(buf), bfp);
  3042. if (ret > 0)
  3043. {
  3044. ret = gzwrite(gzfp, (voidp)buf, ret);
  3045. if (ret <= 0)
  3046. {
  3047. wm_tool_printf("can not write gzip binary.\r\n");
  3048. return -2;
  3049. }
  3050. }
  3051. } while (ret > 0);
  3052. gzclose(gzfp);
  3053. fclose(bfp);
  3054. wm_tool_printf("compress binary completed.\r\n");
  3055. return 0;
  3056. }
  3057. static int wm_tool_pack_firmware(void)
  3058. {
  3059. int ret;
  3060. char *path;
  3061. char *name;
  3062. char *image;
  3063. char *gzbin;
  3064. char *gzimg;
  3065. char *dbgimg;
  3066. char *fls;
  3067. if (!wm_tool_input_binary)
  3068. return 1;
  3069. if (!wm_tool_output_image)
  3070. {
  3071. char *r = wm_tool_input_binary;
  3072. char *t = wm_tool_input_binary;
  3073. do
  3074. {
  3075. r = strchr(r, '.');
  3076. if (r)
  3077. {
  3078. t = r;
  3079. r++;
  3080. }
  3081. } while (r);
  3082. wm_tool_output_image = malloc(t - wm_tool_input_binary + 1);
  3083. if (!wm_tool_output_image)
  3084. return -1;
  3085. memcpy(wm_tool_output_image, wm_tool_input_binary, t - wm_tool_input_binary);
  3086. wm_tool_output_image[t - wm_tool_input_binary] = '\0';
  3087. }
  3088. char *p = wm_tool_output_image;
  3089. char *q = wm_tool_output_image;
  3090. do
  3091. {
  3092. p = strchr(p, '/');
  3093. if (p)
  3094. {
  3095. p++;
  3096. q = p;
  3097. }
  3098. } while (p);
  3099. /* output file */
  3100. name = strdup(q);
  3101. *q = '\0';
  3102. path = strdup(wm_tool_output_image);
  3103. image = malloc(strlen(path) + strlen(name) + strlen(".img") + 1);
  3104. if (!image)
  3105. return -1;
  3106. sprintf(image, "%s%s.img", path, name);
  3107. if (WM_TOOL_ZIP_TYPE_UNCOMPRESS == wm_tool_zip_type)
  3108. {
  3109. ret = wm_tool_pack_image(image);
  3110. if (ret)
  3111. return ret;
  3112. }
  3113. if (WM_TOOL_ZIP_TYPE_COMPRESS == wm_tool_zip_type)
  3114. {
  3115. gzbin = malloc(strlen(path) + strlen(name) + strlen("_gz.bin") + 1);
  3116. gzimg = malloc(strlen(path) + strlen(name) + strlen("_gz.img") + 1);
  3117. if (!gzbin || !gzimg)
  3118. return -1;
  3119. sprintf(gzbin, "%s%s.bin.gz", path, name);
  3120. sprintf(gzimg, "%s%s_gz.img", path, name);
  3121. ret = wm_tool_gzip_bin(wm_tool_input_binary, gzbin);
  3122. if (ret)
  3123. return ret;
  3124. ret = wm_tool_pack_gz_image(gzbin, gzimg);
  3125. free(gzbin);
  3126. free(gzimg);
  3127. if (ret)
  3128. return ret;
  3129. }
  3130. if (wm_tool_is_debug)
  3131. {
  3132. dbgimg = malloc(strlen(path) + strlen(name) + strlen("_dbg.img") + 1);
  3133. if (!dbgimg)
  3134. return -1;
  3135. sprintf(dbgimg, "%s%s_dbg.img", path, name);
  3136. ret = wm_tool_pack_dbg_image(image, dbgimg);
  3137. free(dbgimg);
  3138. if (ret)
  3139. return ret;
  3140. }
  3141. if (wm_tool_secboot_image)
  3142. {
  3143. fls = malloc(strlen(path) + strlen(name) + strlen(".fls") + 1);
  3144. if (!fls)
  3145. return -1;
  3146. sprintf(fls, "%s%s.fls", path, name);
  3147. ret = wm_tool_pack_fls(image, fls);
  3148. free(fls);
  3149. }
  3150. free(image);
  3151. return ret;
  3152. }
  3153. #ifdef __MINGW32__
  3154. static BOOL wm_tool_signal_proc(DWORD no)
  3155. {
  3156. switch (no)
  3157. {
  3158. case CTRL_C_EVENT:
  3159. wm_tool_signal_proc_entry();
  3160. return(FALSE);
  3161. default:
  3162. return FALSE;
  3163. }
  3164. }
  3165. static void wm_tool_signal_init(void)
  3166. {
  3167. SetConsoleCtrlHandler((PHANDLER_ROUTINE)wm_tool_signal_proc, TRUE);
  3168. }
  3169. static void wm_tool_delay_ms(int ms)
  3170. {
  3171. Sleep(ms);
  3172. return;
  3173. }
  3174. static int wm_tool_uart_set_rts(int boolflag)
  3175. {
  3176. return EscapeCommFunction(wm_tool_uart_handle,((boolflag) ? SETRTS : CLRRTS)) ? 0 : -1;
  3177. }
  3178. static int wm_tool_uart_set_dtr(int boolflag)
  3179. {
  3180. return EscapeCommFunction(wm_tool_uart_handle,((boolflag) ? SETDTR : CLRDTR)) ? 0 : -1;
  3181. }
  3182. static int wm_tool_uart_set_timeout(void)
  3183. {
  3184. BOOL ret;
  3185. COMMTIMEOUTS timeout;
  3186. timeout.ReadIntervalTimeout = MAXDWORD;
  3187. timeout.ReadTotalTimeoutConstant = 0;
  3188. timeout.ReadTotalTimeoutMultiplier = 0;
  3189. timeout.WriteTotalTimeoutConstant = 0;
  3190. timeout.WriteTotalTimeoutMultiplier = 0;
  3191. ret = SetCommTimeouts(wm_tool_uart_handle, &timeout);
  3192. if (ret)
  3193. ret = SetCommMask(wm_tool_uart_handle, EV_TXEMPTY);
  3194. return ret ? 0 : -1;
  3195. }
  3196. static void wm_tool_uart_set_block(int bolck)
  3197. {
  3198. if (bolck)
  3199. wm_tool_uart_block = INFINITE;
  3200. else
  3201. wm_tool_uart_block = 0;
  3202. return;
  3203. }
  3204. static int wm_tool_uart_set_speed(int speed)
  3205. {
  3206. int i;
  3207. int size;
  3208. DCB cfg;
  3209. size = sizeof(wm_tool_uart_speed_array) / sizeof(int);
  3210. for (i= 0; i < size; i++)
  3211. {
  3212. if (speed == wm_tool_uart_name_array[i])
  3213. {
  3214. if (GetCommState(wm_tool_uart_handle, &cfg))
  3215. {
  3216. cfg.DCBlength = sizeof(DCB);
  3217. cfg.BaudRate = wm_tool_uart_speed_array[i];
  3218. cfg.fBinary = TRUE;
  3219. cfg.fParity = FALSE;
  3220. cfg.fDtrControl = DTR_CONTROL_DISABLE;
  3221. cfg.fDsrSensitivity = FALSE;
  3222. cfg.fRtsControl = RTS_CONTROL_DISABLE;
  3223. cfg.ByteSize = 8;
  3224. cfg.StopBits = ONESTOPBIT;
  3225. cfg.fAbortOnError = FALSE;
  3226. cfg.fOutX = FALSE;
  3227. cfg.fInX = FALSE;
  3228. cfg.fErrorChar = FALSE;
  3229. cfg.fNull = FALSE;
  3230. cfg.fOutxCtsFlow = FALSE;
  3231. cfg.fOutxDsrFlow = FALSE;
  3232. cfg.Parity = NOPARITY;
  3233. cfg.fTXContinueOnXoff = FALSE;
  3234. return SetCommState(wm_tool_uart_handle, &cfg) ? 0 : -1;
  3235. }
  3236. else
  3237. {
  3238. return -3;
  3239. }
  3240. }
  3241. }
  3242. return -2;
  3243. }
  3244. static void wm_tool_uart_clear(void)
  3245. {
  3246. PurgeComm(wm_tool_uart_handle, PURGE_RXCLEAR);
  3247. return;
  3248. }
  3249. static int wm_tool_uart_open(const char *device)
  3250. {
  3251. BOOL ret;
  3252. char name[40];
  3253. sprintf(name,"\\\\.\\%s", device);
  3254. wm_tool_uart_handle = CreateFile(name, GENERIC_WRITE | GENERIC_READ,
  3255. 0, NULL, OPEN_EXISTING,
  3256. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
  3257. NULL);
  3258. if (wm_tool_uart_handle == INVALID_HANDLE_VALUE)
  3259. {
  3260. return -1;
  3261. }
  3262. ret = SetupComm(wm_tool_uart_handle, 4096, 4096);
  3263. if (ret)
  3264. {
  3265. ret = wm_tool_uart_set_speed(WM_TOOL_DEFAULT_BAUD_RATE);
  3266. ret |= wm_tool_uart_set_timeout();
  3267. }
  3268. else
  3269. {
  3270. ret = -1;
  3271. }
  3272. return ret;
  3273. }
  3274. static int wm_tool_uart_read(void *data, unsigned int size)
  3275. {
  3276. BOOL ret;
  3277. DWORD wait;
  3278. unsigned long len = 0;
  3279. COMSTAT state;
  3280. DWORD error;
  3281. OVERLAPPED event;
  3282. do
  3283. {
  3284. memset(&event, 0, sizeof(OVERLAPPED));
  3285. event.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  3286. ClearCommError(wm_tool_uart_handle, &error, &state);
  3287. ret = ReadFile(wm_tool_uart_handle, data, size, &len, &event);
  3288. if (!ret)
  3289. {
  3290. if (ERROR_IO_PENDING == GetLastError())
  3291. {
  3292. wait = WaitForSingleObject(event.hEvent, wm_tool_uart_block);
  3293. if (WAIT_OBJECT_0 == wait)
  3294. ret = TRUE;
  3295. }
  3296. }
  3297. } while (wm_tool_uart_block && !len);
  3298. if (ret)
  3299. {
  3300. if (len > 0)
  3301. return (int)len;
  3302. }
  3303. return -1;
  3304. }
  3305. static int wm_tool_uart_write(const void *data, unsigned int size)
  3306. {
  3307. BOOL ret;
  3308. DWORD wait;
  3309. OVERLAPPED event;
  3310. COMSTAT state;
  3311. DWORD error;
  3312. unsigned int snd = 0;
  3313. unsigned long len = 0;
  3314. memset(&event, 0, sizeof(OVERLAPPED));
  3315. event.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  3316. do
  3317. {
  3318. ClearCommError(wm_tool_uart_handle, &error, &state);
  3319. ret = WriteFile(wm_tool_uart_handle, data + snd, size - snd, &len, &event);
  3320. if (!ret)
  3321. {
  3322. if (ERROR_IO_PENDING == GetLastError())
  3323. {
  3324. wait = WaitForSingleObject(event.hEvent, INFINITE);
  3325. if (WAIT_OBJECT_0 == wait)
  3326. ret = TRUE;
  3327. }
  3328. }
  3329. if (ret)
  3330. {
  3331. if ((len > 0) && (snd != size))
  3332. {
  3333. snd += len;
  3334. }
  3335. else
  3336. {
  3337. return size;
  3338. }
  3339. }
  3340. else
  3341. {
  3342. break;
  3343. }
  3344. } while (1);
  3345. return -1;
  3346. }
  3347. static void wm_tool_uart_close(void)
  3348. {
  3349. FlushFileBuffers(wm_tool_uart_handle);
  3350. CloseHandle(wm_tool_uart_handle);
  3351. wm_tool_uart_handle = NULL;
  3352. return;
  3353. }
  3354. static DWORD WINAPI wm_tool_uart_tx_thread(LPVOID arg)
  3355. {
  3356. wm_tool_stdin_to_uart();
  3357. return 0;
  3358. }
  3359. static int wm_tool_create_thread(void)
  3360. {
  3361. HANDLE thread_handle;
  3362. thread_handle = CreateThread(0, 0, wm_tool_uart_tx_thread, NULL, 0, NULL);
  3363. CloseHandle(thread_handle);
  3364. return 0;
  3365. }
  3366. #else
  3367. static void wm_tool_signal_proc(int no)
  3368. {
  3369. wm_tool_signal_proc_entry();
  3370. }
  3371. static void wm_tool_signal_init(void)
  3372. {
  3373. signal(SIGINT, wm_tool_signal_proc);
  3374. }
  3375. static void wm_tool_delay_ms(int ms)
  3376. {
  3377. usleep(ms * 1000);
  3378. return;
  3379. }
  3380. static int wm_tool_uart_set_rts(int boolflag)
  3381. {
  3382. int ret;
  3383. int controlbits;
  3384. ret = ioctl(wm_tool_uart_fd, TIOCMGET, &controlbits);
  3385. if (ret < 0)
  3386. {
  3387. WM_TOOL_DBG_PRINT("TIOCMGET failed!\r\n");
  3388. return ret;
  3389. }
  3390. if (controlbits & TIOCM_RTS)
  3391. {
  3392. WM_TOOL_DBG_PRINT("TIOCM_RTS!, %d!\r\n", boolflag);
  3393. }
  3394. else
  3395. {
  3396. WM_TOOL_DBG_PRINT("~TIOCM_RTS!, %d!\r\n", boolflag);
  3397. }
  3398. if (boolflag)
  3399. controlbits |= TIOCM_RTS;
  3400. else
  3401. controlbits &= ~TIOCM_RTS;
  3402. ret = ioctl(wm_tool_uart_fd, TIOCMSET, &controlbits);
  3403. if (ret < 0)
  3404. {
  3405. WM_TOOL_DBG_PRINT("TIOCMSET failed!\r\n");
  3406. }
  3407. if (ret >= 0)
  3408. ret = 0;
  3409. return ret;
  3410. }
  3411. static int wm_tool_uart_set_dtr(int boolflag)
  3412. {
  3413. int ret;
  3414. int controlbits;
  3415. ret = ioctl(wm_tool_uart_fd, TIOCMGET, &controlbits);
  3416. if (ret < 0)
  3417. {
  3418. WM_TOOL_DBG_PRINT("TIOCMGET failed!\r\n");
  3419. return ret;
  3420. }
  3421. if (controlbits & TIOCM_DTR)
  3422. {
  3423. WM_TOOL_DBG_PRINT("TIOCM_DTR, %d!\r\n", boolflag);
  3424. }
  3425. else
  3426. {
  3427. WM_TOOL_DBG_PRINT("~TIOCM_DTR, %d!\r\n", boolflag);
  3428. }
  3429. if (boolflag)
  3430. controlbits |= TIOCM_DTR;
  3431. else
  3432. controlbits &= ~TIOCM_DTR;
  3433. ret = ioctl(wm_tool_uart_fd, TIOCMSET, &controlbits);
  3434. if (ret < 0)
  3435. {
  3436. WM_TOOL_DBG_PRINT("TIOCMSET failed!\r\n");
  3437. }
  3438. if (ret >= 0)
  3439. ret = 0;
  3440. return ret;
  3441. }
  3442. static void wm_tool_uart_set_block(int bolck)
  3443. {
  3444. int comopt;
  3445. comopt = fcntl(wm_tool_uart_fd, F_GETFL, 0);
  3446. if (bolck)
  3447. fcntl(wm_tool_uart_fd, F_SETFL, comopt & ~O_NDELAY);
  3448. else
  3449. fcntl(wm_tool_uart_fd, F_SETFL, comopt | O_NDELAY);
  3450. return;
  3451. }
  3452. static int wm_tool_uart_set_speed(int speed)
  3453. {
  3454. int i;
  3455. int size;
  3456. int status = -1;
  3457. struct termios opt;
  3458. tcgetattr(wm_tool_uart_fd, &opt);
  3459. size = sizeof(wm_tool_uart_speed_array) / sizeof(int);
  3460. for (i= 0; i < size; i++)
  3461. {
  3462. if (speed == wm_tool_uart_name_array[i])
  3463. {
  3464. cfsetispeed(&opt, wm_tool_uart_speed_array[i]);
  3465. cfsetospeed(&opt, wm_tool_uart_speed_array[i]);
  3466. status = tcsetattr(wm_tool_uart_fd, TCSANOW, &opt);
  3467. break;
  3468. }
  3469. }
  3470. return status;
  3471. }
  3472. static void wm_tool_uart_clear(void)
  3473. {
  3474. tcflush(wm_tool_uart_fd, TCIFLUSH);
  3475. return;
  3476. }
  3477. static int wm_tool_uart_open(const char *device)
  3478. {
  3479. struct termios tty;
  3480. wm_tool_uart_fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY);
  3481. if (-1 == wm_tool_uart_fd)
  3482. {
  3483. return -1;
  3484. }
  3485. tcgetattr(wm_tool_uart_fd, &wm_tool_saved_serial_cfg);
  3486. wm_tool_uart_set_dtr(0);
  3487. tcgetattr(wm_tool_uart_fd, &tty);
  3488. /* databit 8bit */
  3489. tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
  3490. /* set into raw, no echo mode */
  3491. tty.c_iflag = IGNBRK;
  3492. tty.c_lflag = 0;
  3493. tty.c_oflag = 0;
  3494. tty.c_cflag |= CLOCAL | CREAD;
  3495. tty.c_cflag &= ~CRTSCTS;
  3496. tty.c_cc[VMIN] = 1;
  3497. tty.c_cc[VTIME] = 5;
  3498. /* have no software flow control */
  3499. tty.c_iflag &= ~(IXON|IXOFF|IXANY);
  3500. /* parity none */
  3501. tty.c_cflag &= ~(PARENB | PARODD);
  3502. /* stopbit 1bit */
  3503. tty.c_cflag &= ~CSTOPB;
  3504. tcsetattr(wm_tool_uart_fd, TCSANOW, &tty);
  3505. return wm_tool_uart_set_speed(WM_TOOL_DEFAULT_BAUD_RATE);
  3506. }
  3507. static int wm_tool_uart_read(void *data, unsigned int size)
  3508. {
  3509. return read(wm_tool_uart_fd, data, size);
  3510. }
  3511. static int wm_tool_uart_write(const void *data, unsigned int size)
  3512. {
  3513. int snd = 0;
  3514. int ret = 0;
  3515. do
  3516. {
  3517. ret = write(wm_tool_uart_fd, data + snd, size - snd);
  3518. if (ret > 0)
  3519. {
  3520. snd += ret;
  3521. if (snd == size)
  3522. {
  3523. return size;
  3524. }
  3525. }
  3526. else
  3527. {
  3528. break;
  3529. }
  3530. } while (1);
  3531. return -1;
  3532. }
  3533. static void wm_tool_uart_close(void)
  3534. {
  3535. tcsetattr(wm_tool_uart_fd, TCSANOW, &wm_tool_saved_serial_cfg);
  3536. tcdrain(wm_tool_uart_fd);
  3537. tcflush(wm_tool_uart_fd, TCIOFLUSH);
  3538. close(wm_tool_uart_fd);
  3539. wm_tool_uart_fd = -1;
  3540. return;
  3541. }
  3542. static void *wm_tool_uart_tx_thread(void *arg)
  3543. {
  3544. wm_tool_stdin_to_uart();
  3545. return NULL;
  3546. }
  3547. static int wm_tool_create_thread(void)
  3548. {
  3549. pthread_t thread_id;
  3550. return pthread_create(&thread_id, NULL, wm_tool_uart_tx_thread, NULL);
  3551. }
  3552. #endif
  3553. static void wm_tool_signal_proc_entry(void)
  3554. {
  3555. WM_TOOL_DBG_PRINT("signal exit.\r\n");
  3556. exit(0);
  3557. }
  3558. static void wm_tool_stdin_to_uart(void)
  3559. {
  3560. int ret;
  3561. char buf[WM_TOOL_ONCE_READ_LEN];
  3562. while (1)
  3563. {
  3564. if (fgets(buf, WM_TOOL_ONCE_READ_LEN, stdin))
  3565. {
  3566. ret = wm_tool_uart_write(buf, strlen(buf));
  3567. if (ret <= 0)
  3568. {
  3569. WM_TOOL_DBG_PRINT("failed to write [%s].\r\n", buf);
  3570. }
  3571. }
  3572. }
  3573. return;
  3574. }
  3575. static int wm_tool_show_log_from_serial(void)
  3576. {
  3577. int i;
  3578. int ret;
  3579. unsigned int j = 0;
  3580. unsigned char buf[WM_TOOL_ONCE_READ_LEN + 1];
  3581. ret = wm_tool_uart_open(wm_tool_serial_path);
  3582. if (ret)
  3583. {
  3584. wm_tool_printf("can not open serial\r\n");
  3585. return ret;
  3586. }
  3587. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_normal_serial_rate)
  3588. {
  3589. ret = wm_tool_uart_set_speed(wm_tool_normal_serial_rate);
  3590. if (ret)
  3591. {
  3592. wm_tool_printf("can not set serial baud rate.\r\n");
  3593. wm_tool_uart_close();
  3594. return ret;
  3595. }
  3596. }
  3597. ret = wm_tool_create_thread();
  3598. if (ret)
  3599. {
  3600. wm_tool_printf("can not create thread.\r\n");
  3601. wm_tool_uart_close();
  3602. return ret;
  3603. }
  3604. wm_tool_uart_set_block(0);
  3605. wm_tool_signal_init();
  3606. while (1)
  3607. {
  3608. ret = wm_tool_uart_read(buf, WM_TOOL_ONCE_READ_LEN);
  3609. if (ret > 0)
  3610. {
  3611. if (WM_TOOL_SHOW_LOG_STR == wm_tool_show_log_type)
  3612. {
  3613. buf[ret] = '\0';
  3614. wm_tool_printf("%s", (char *)buf);
  3615. }
  3616. else if (WM_TOOL_SHOW_LOG_HEX == wm_tool_show_log_type)
  3617. {
  3618. for (i = 0; i < ret; i++, j++)
  3619. {
  3620. wm_tool_printf("%02X ", buf[i]);
  3621. if ((j + 1) % 16 == 0)
  3622. {
  3623. wm_tool_printf("\r\n");
  3624. }
  3625. }
  3626. }
  3627. else
  3628. {
  3629. break;
  3630. }
  3631. }
  3632. else
  3633. {
  3634. wm_tool_delay_ms(1);
  3635. }
  3636. }
  3637. wm_tool_uart_close();
  3638. return ret;
  3639. }
  3640. static int wm_tool_set_wifi_chip_speed(int speed)
  3641. {
  3642. int ret;
  3643. if (2000000 == speed)
  3644. {
  3645. ret = wm_tool_uart_write(wm_tool_chip_cmd_b2000000, sizeof(wm_tool_chip_cmd_b2000000));
  3646. }
  3647. else if (1000000 == speed)
  3648. {
  3649. ret = wm_tool_uart_write(wm_tool_chip_cmd_b1000000, sizeof(wm_tool_chip_cmd_b1000000));
  3650. }
  3651. else if (921600 == speed)
  3652. {
  3653. ret = wm_tool_uart_write(wm_tool_chip_cmd_b921600, sizeof(wm_tool_chip_cmd_b921600));
  3654. }
  3655. else if (460800 == speed)
  3656. {
  3657. ret = wm_tool_uart_write(wm_tool_chip_cmd_b460800, sizeof(wm_tool_chip_cmd_b460800));
  3658. }
  3659. else
  3660. {
  3661. ret = wm_tool_uart_write(wm_tool_chip_cmd_b115200, sizeof(wm_tool_chip_cmd_b115200));
  3662. }
  3663. return ret;
  3664. }
  3665. static int wm_tool_send_esc2uart(int ms)
  3666. {
  3667. int i;
  3668. int err = 0;
  3669. unsigned char esc_key = 27;
  3670. for (i = 0; i < (ms / 10); i++)
  3671. {
  3672. err = wm_tool_uart_write(&esc_key, 1);
  3673. wm_tool_delay_ms(10);/* 10-50ms */
  3674. }
  3675. return err;
  3676. }
  3677. static int wm_tool_erase_image(wm_tool_dl_erase_e type)
  3678. {
  3679. int cnt = 0;
  3680. int ret = -1;
  3681. unsigned char ch;
  3682. unsigned char rom_cmd[] = {0x21, 0x0a, 0x00, 0xc3, 0x35, 0x32, 0x00, 0x00, 0x00, 0x02, 0x00, 0xfe, 0x01}; /*2M-8k*/
  3683. WM_TOOL_DBG_PRINT("start erase.\r\n");
  3684. if (WM_TOOL_DL_ERASE_ALL == type)
  3685. {
  3686. wm_tool_printf("erase flash...\r\n");
  3687. ret = wm_tool_uart_write(rom_cmd, sizeof(rom_cmd));
  3688. }
  3689. if (ret <= 0)
  3690. return -1;
  3691. wm_tool_uart_clear();
  3692. wm_tool_uart_set_block(1);
  3693. do
  3694. {
  3695. ret = wm_tool_uart_read(&ch, 1);
  3696. if (ret > 0)
  3697. {
  3698. if (('C' == ch) || ('P' == ch))
  3699. cnt++;
  3700. else
  3701. cnt = 0;
  3702. }
  3703. else
  3704. {
  3705. wm_tool_printf("erase error, errno = %d.\r\n", errno);
  3706. return -2;
  3707. }
  3708. } while (cnt < 3);
  3709. wm_tool_uart_set_block(0);
  3710. wm_tool_printf("erase finish.\r\n");
  3711. return 0;
  3712. }
  3713. static int wm_tool_query_mac(void)
  3714. {
  3715. int ret = -1;
  3716. int err;
  3717. int offset = 0;
  3718. char macstr[32] = {0};
  3719. int len = strlen("MAC:AABBCCDDEEFF\n");/* resp format, ROM "Mac:AABBCCDDEEFF\n", SECBOOT "MAC:AABBCCDDEEFF\n" */
  3720. unsigned char macaddr[6] = {0};
  3721. wm_tool_uart_clear();
  3722. wm_tool_uart_set_block(1);
  3723. err = wm_tool_uart_write(wm_tool_chip_cmd_get_mac, sizeof(wm_tool_chip_cmd_get_mac));
  3724. if (err > 0)
  3725. {
  3726. do
  3727. {
  3728. err = wm_tool_uart_read((unsigned char *)(macstr + offset), sizeof(macstr) - 1 - offset);
  3729. if (err > 0)
  3730. {
  3731. offset += err;
  3732. if (offset >= len)
  3733. {
  3734. macstr[len - 1] = '\0';/* \n -> 0 */
  3735. err = wm_tool_str_to_hex_array(macstr + strlen("MAC:"), 6, macaddr);
  3736. if (!err)
  3737. {
  3738. wm_tool_printf("mac %02X-%02X-%02X-%02X-%02X-%02X.\r\n", macaddr[0],
  3739. macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]);
  3740. if (!strncmp(macstr, "Mac:", strlen("Mac:")) &&
  3741. (WM_TOOL_DL_TYPE_FLS != wm_tool_dl_type) &&
  3742. !wm_tool_dl_erase)
  3743. {
  3744. wm_tool_printf("please download the firmware in .fls format.\r\n");
  3745. }
  3746. else
  3747. {
  3748. ret = 0;
  3749. }
  3750. }
  3751. break;
  3752. }
  3753. }
  3754. } while (err > 0);
  3755. }
  3756. wm_tool_uart_set_block(0);
  3757. return ret;
  3758. }
  3759. static int wm_tool_xmodem_download(const char *image)
  3760. {
  3761. FILE *imgfp;
  3762. unsigned char packet_data[XMODEM_DATA_SIZE];
  3763. unsigned char frame_data[XMODEM_DATA_SIZE + XMODEM_CRC_SIZE + XMODEM_FRAME_ID_SIZE + 1];
  3764. int complete, retry_num, pack_counter, read_number, write_number = 0, i;
  3765. unsigned short crc_value;
  3766. unsigned char ack_id;
  3767. int sndlen;
  3768. int ret = -111;
  3769. imgfp = fopen(image, "rb");
  3770. if (!imgfp)
  3771. {
  3772. wm_tool_printf("can not open image to download.\r\n");
  3773. return -1;
  3774. }
  3775. sndlen = 0;
  3776. pack_counter = 0;
  3777. complete = 0;
  3778. retry_num = 0;
  3779. wm_tool_printf("start download.\r\n");
  3780. wm_tool_printf("download 0%%\r\n");
  3781. wm_tool_uart_clear();
  3782. wm_tool_uart_set_block(1);
  3783. ack_id = XMODEM_ACK;
  3784. while (!complete)
  3785. {
  3786. WM_TOOL_DBG_PRINT("switch ack_id = %x\r\n", ack_id);
  3787. switch(ack_id)
  3788. {
  3789. case XMODEM_ACK:
  3790. {
  3791. retry_num = 0;
  3792. pack_counter++;
  3793. read_number = fread(packet_data, sizeof(char), XMODEM_DATA_SIZE, imgfp);
  3794. WM_TOOL_DBG_PRINT("fread = %d\r\n", read_number);
  3795. if (read_number > 0)
  3796. {
  3797. sndlen += read_number;
  3798. if (read_number < XMODEM_DATA_SIZE)
  3799. {
  3800. WM_TOOL_DBG_PRINT("start filling the last frame!\r\n");
  3801. for ( ; read_number < XMODEM_DATA_SIZE; read_number++)
  3802. packet_data[read_number] = 0x0;
  3803. }
  3804. frame_data[0] = XMODEM_HEAD;
  3805. frame_data[1] = (char)pack_counter;
  3806. frame_data[2] = (char)(255 - frame_data[1]);
  3807. for (i = 0; i < XMODEM_DATA_SIZE; i++)
  3808. frame_data[i + 3] = packet_data[i];
  3809. crc_value = wm_tool_get_crc16(packet_data, XMODEM_DATA_SIZE);
  3810. frame_data[XMODEM_DATA_SIZE + 3]=(unsigned char)(crc_value >> 8);
  3811. frame_data[XMODEM_DATA_SIZE + 4]=(unsigned char)(crc_value);
  3812. write_number = wm_tool_uart_write(frame_data, XMODEM_DATA_SIZE + 5);
  3813. if (write_number <= 0)
  3814. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3815. WM_TOOL_DBG_PRINT("waiting for ack, %d, %d ...\r\n", pack_counter, write_number);
  3816. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3817. if (ack_id == XMODEM_ACK)
  3818. {
  3819. WM_TOOL_DBG_PRINT("Ok!\r\n");
  3820. if (sndlen % 10240 == 0)
  3821. {
  3822. //wm_tool_printf("#");
  3823. wm_tool_printf("#download %d%%\r\n", sndlen >= 1024*1000 ? 99 : sndlen / (10240));
  3824. }
  3825. }
  3826. else
  3827. {
  3828. WM_TOOL_DBG_PRINT("error = %x!\r\n", ack_id);
  3829. }
  3830. }
  3831. else
  3832. {
  3833. ack_id = XMODEM_EOT;
  3834. complete = 1;
  3835. WM_TOOL_DBG_PRINT("waiting for complete ack ...\r\n");
  3836. while (ack_id != XMODEM_ACK)
  3837. {
  3838. ack_id = XMODEM_EOT;
  3839. write_number = wm_tool_uart_write(&ack_id, 1);
  3840. if (write_number <= 0)
  3841. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3842. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3843. }
  3844. WM_TOOL_DBG_PRINT("ok\r\n");
  3845. wm_tool_printf("download 100%%\r\n");
  3846. //wm_tool_printf("download completed.\r\n");
  3847. ret = 0;
  3848. }
  3849. break;
  3850. }
  3851. case XMODEM_NAK:
  3852. {
  3853. if ( retry_num++ > 100)
  3854. {
  3855. WM_TOOL_DBG_PRINT("retry too many times, quit!\r\n");
  3856. wm_tool_printf("download firmware timeout.\r\n");
  3857. complete = 1;
  3858. }
  3859. else
  3860. {
  3861. write_number = wm_tool_uart_write(frame_data, XMODEM_DATA_SIZE + 5);
  3862. if (write_number <= 0)
  3863. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3864. WM_TOOL_DBG_PRINT("retry for ack, %d, %d ...\r\n", pack_counter, write_number);
  3865. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3866. if (ack_id == XMODEM_ACK)
  3867. {
  3868. WM_TOOL_DBG_PRINT("ok\r\n");
  3869. }
  3870. else
  3871. {
  3872. WM_TOOL_DBG_PRINT("error!\r\n");
  3873. }
  3874. }
  3875. break;
  3876. }
  3877. default:
  3878. {
  3879. WM_TOOL_DBG_PRINT("fatal error!\r\n");
  3880. WM_TOOL_DBG_PRINT("unknown xmodem protocal [%x].\r\n", ack_id);
  3881. wm_tool_printf("\r\ndownload failed, please reset and try again.\r\n");
  3882. complete = 1;
  3883. break;
  3884. }
  3885. }
  3886. }
  3887. wm_tool_uart_set_block(0);
  3888. fclose(imgfp);
  3889. return ret;
  3890. }
  3891. static int wm_tool_download_firmware(void)
  3892. {
  3893. int ret;
  3894. int cnt = 0;
  3895. int note = 1;
  3896. int timeout = 0;
  3897. float timeuse;
  3898. time_t start, end;
  3899. unsigned char ch;
  3900. wm_tool_printf("connecting serial...\r\n");
  3901. ret = wm_tool_uart_open(wm_tool_serial_path);
  3902. if (ret)
  3903. {
  3904. wm_tool_printf("can not open serial\r\n");
  3905. return ret;
  3906. }
  3907. /* In some cases, setting the serial port initialization setting requires a delay. */
  3908. wm_tool_delay_ms(500);
  3909. wm_tool_printf("serial connected.\r\n");
  3910. if (WM_TOOL_DL_ACTION_AT == wm_tool_dl_action)
  3911. {
  3912. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_normal_serial_rate)
  3913. wm_tool_uart_set_speed(wm_tool_normal_serial_rate);
  3914. #if 0 /* use erase option */
  3915. if (WM_TOOL_DL_TYPE_FLS == wm_tool_dl_type)
  3916. {
  3917. ret = wm_tool_uart_write("AT+&FLSW=8002000,0\r\n", strlen("AT+&FLSW=8002000,0\r\n"));
  3918. if (ret <= 0)
  3919. {
  3920. wm_tool_printf("destroy secboot failed.\r\n");
  3921. wm_tool_uart_close();
  3922. return -3;
  3923. }
  3924. wm_tool_delay_ms(300);
  3925. }
  3926. #endif
  3927. ret = wm_tool_uart_write("AT+Z\r\n", strlen("AT+Z\r\n"));
  3928. if (ret <= 0)
  3929. {
  3930. wm_tool_printf("reset error.\r\n");
  3931. wm_tool_uart_close();
  3932. return -4;
  3933. }
  3934. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_normal_serial_rate)
  3935. wm_tool_uart_set_speed(WM_TOOL_DEFAULT_BAUD_RATE);
  3936. }
  3937. else if (WM_TOOL_DL_ACTION_RTS == wm_tool_dl_action)
  3938. {
  3939. ret = wm_tool_uart_set_dtr(0);
  3940. ret |= wm_tool_uart_set_rts(1);
  3941. wm_tool_delay_ms(50);
  3942. ret |= wm_tool_uart_set_dtr(1);
  3943. ret |= wm_tool_uart_set_rts(0);
  3944. wm_tool_delay_ms(50);
  3945. ret |= wm_tool_uart_set_dtr(0);
  3946. if (ret < 0)
  3947. {
  3948. wm_tool_printf("set rts to reboot error.\r\n");
  3949. wm_tool_uart_close();
  3950. return -5;
  3951. }
  3952. }
  3953. wm_tool_printf("wait serial sync...");
  3954. wm_tool_send_esc2uart(500);/* used for delay */
  3955. start = time(NULL);
  3956. do
  3957. {
  3958. ret = wm_tool_uart_read(&ch, 1);
  3959. WM_TOOL_DBG_PRINT("ret=%d, %x-%c\r\n", ret, ch, ch);
  3960. if (ret > 0)
  3961. {
  3962. if (('C' == ch) || ('P' == ch))
  3963. cnt++;
  3964. else
  3965. cnt = 0;
  3966. }
  3967. else
  3968. {
  3969. wm_tool_send_esc2uart(30);
  3970. }
  3971. end = time(NULL);
  3972. timeuse = difftime(end, start);
  3973. if (timeuse >= 1)
  3974. {
  3975. wm_tool_printf(".");
  3976. if ((((int)timeuse) % 2) == 0) {
  3977. wm_tool_uart_set_rts(0);
  3978. }
  3979. else {
  3980. wm_tool_uart_set_rts(1);
  3981. }
  3982. wm_tool_send_esc2uart(0);
  3983. timeout++;
  3984. if ((timeout >= (WM_TOOL_DOWNLOAD_TIMEOUT_SEC / 10)) && note)
  3985. {
  3986. wm_tool_printf("\r\nplease manually reset the device.\r\n");
  3987. note = 0;
  3988. }
  3989. else if (timeout > WM_TOOL_DOWNLOAD_TIMEOUT_SEC)
  3990. {
  3991. wm_tool_uart_close();
  3992. wm_tool_printf("\r\nserial sync timeout.\r\n");
  3993. return -6;
  3994. }
  3995. start = time(NULL);
  3996. }
  3997. } while (cnt < 3);
  3998. wm_tool_printf("\r\nserial sync sucess.\r\n");
  3999. // ret = wm_tool_query_mac();
  4000. // if (ret)
  4001. // {
  4002. // wm_tool_uart_close();
  4003. // wm_tool_printf("download failed.\r\n");
  4004. // return ret;
  4005. // }
  4006. if (WM_TOOL_DL_ERASE_ALL == wm_tool_dl_erase)
  4007. {
  4008. ret = wm_tool_erase_image(WM_TOOL_DL_ERASE_ALL);
  4009. if (ret)
  4010. {
  4011. wm_tool_uart_close();
  4012. wm_tool_printf("failed to erase.\r\n");
  4013. return ret;
  4014. }
  4015. }
  4016. if (!wm_tool_download_image && wm_tool_dl_erase)
  4017. {
  4018. return 0;
  4019. }
  4020. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_download_serial_rate)
  4021. {
  4022. ret = wm_tool_set_wifi_chip_speed(wm_tool_download_serial_rate);
  4023. if (ret > 0)
  4024. {
  4025. wm_tool_delay_ms(1 * 1000);
  4026. wm_tool_uart_set_speed(wm_tool_download_serial_rate);
  4027. }
  4028. }
  4029. ret = wm_tool_xmodem_download(wm_tool_download_image);
  4030. if (ret == 0) {
  4031. wm_tool_delay_ms(200);
  4032. // 21 06 00 c7 7c 3f 00 00 00
  4033. wm_tool_uart_write(wm_tool_chip_cmd_reset, sizeof(wm_tool_chip_cmd_reset));
  4034. wm_tool_delay_ms(30);
  4035. wm_tool_printf("download completed.\r\n");
  4036. }
  4037. wm_tool_uart_close();
  4038. return ret;
  4039. }
  4040. static void wm_tool_show_local_com(void)
  4041. {
  4042. #if defined(__APPLE__) && defined(__MACH__)
  4043. char *comstr = "tty.usbserial";
  4044. #elif defined(__CYGWIN__)
  4045. int num;
  4046. char *comstr = "ttyS";
  4047. #elif defined(__linux__)
  4048. char *comstr = "ttyUSB";
  4049. #endif
  4050. #if defined(__APPLE__) || defined(__MACH__) || defined(__CYGWIN__) || defined(__linux__)
  4051. DIR *dir;
  4052. struct dirent *file;
  4053. dir = opendir("/dev");
  4054. if (dir)
  4055. {
  4056. while (NULL != (file = readdir(dir)))
  4057. {
  4058. if ((0 == strncmp(file->d_name, comstr, strlen(comstr))) && (DT_CHR == file->d_type))
  4059. {
  4060. #if defined(__CYGWIN__)
  4061. num = atoi(file->d_name + strlen(comstr));
  4062. wm_tool_printf("COM%d ", num + 1);
  4063. #else
  4064. wm_tool_printf("%s ", file->d_name);
  4065. #endif
  4066. }
  4067. }
  4068. closedir(dir);
  4069. wm_tool_printf("\r\n");
  4070. }
  4071. #elif defined(__MINGW32__)
  4072. LONG ret;
  4073. HKEY key;
  4074. DWORD i = 0;
  4075. DWORD knlen;
  4076. char kname[WM_TOOL_PATH_MAX] = {0};
  4077. DWORD kvlen;
  4078. char kvalue[WM_TOOL_PATH_MAX] = {0};
  4079. REGSAM kmask = KEY_READ;
  4080. #if defined(KEY_WOW64_64KEY)
  4081. BOOL is_64;
  4082. if (IsWow64Process(GetCurrentProcess(), &is_64))
  4083. {
  4084. if (is_64)
  4085. kmask |= KEY_WOW64_64KEY;
  4086. }
  4087. #endif
  4088. ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, NULL, 0, kmask, NULL, &key, NULL);
  4089. if (ret != ERROR_SUCCESS)
  4090. {
  4091. return;
  4092. }
  4093. do{
  4094. knlen = sizeof(kname);
  4095. kvlen = sizeof(kvalue);
  4096. ret = RegEnumValue(key, i, kname, &knlen, 0, NULL, (LPBYTE)kvalue, &kvlen);
  4097. if (ret == ERROR_SUCCESS)
  4098. {
  4099. if (strcmp(kvalue, "") != 0)
  4100. {
  4101. wm_tool_printf("%s ", kvalue);
  4102. }
  4103. }
  4104. i++;
  4105. } while (ret != ERROR_NO_MORE_ITEMS);
  4106. RegCloseKey(key);
  4107. wm_tool_printf("\r\n");
  4108. #else
  4109. wm_tool_printf("\r\nunsupported system.\r\n");
  4110. #endif
  4111. return;
  4112. }
  4113. static void wm_tool_free_res(void)
  4114. {
  4115. if (wm_tool_download_image)
  4116. free(wm_tool_download_image);
  4117. if (wm_tool_output_image)
  4118. free(wm_tool_output_image);
  4119. if (wm_tool_input_binary)
  4120. free(wm_tool_input_binary);
  4121. if (wm_tool_secboot_image)
  4122. free(wm_tool_secboot_image);
  4123. return;
  4124. }
  4125. int main(int argc, char *argv[])
  4126. {
  4127. int ret = 0;
  4128. if (!wm_tool_parse_arv(argc, argv))
  4129. {
  4130. wm_tool_print_usage(argv[0]);
  4131. wm_tool_free_res();
  4132. return 0;
  4133. }
  4134. if (wm_tool_show_usage)
  4135. {
  4136. wm_tool_print_usage(argv[0]);
  4137. wm_tool_free_res();
  4138. return 0;
  4139. }
  4140. if (wm_tool_show_ver)
  4141. {
  4142. wm_tool_print_version(argv[0]);
  4143. wm_tool_free_res();
  4144. return 0;
  4145. }
  4146. if (wm_tool_list_com)
  4147. {
  4148. wm_tool_show_local_com();
  4149. wm_tool_free_res();
  4150. return 0;
  4151. }
  4152. if (wm_tool_input_binary)
  4153. {
  4154. ret = wm_tool_pack_firmware();
  4155. }
  4156. if (wm_tool_download_image || wm_tool_dl_erase)
  4157. {
  4158. ret = wm_tool_download_firmware();
  4159. }
  4160. if (wm_tool_show_log_type)
  4161. {
  4162. ret = wm_tool_show_log_from_serial();
  4163. }
  4164. if (ret > 0)
  4165. wm_tool_print_usage(argv[0]);
  4166. wm_tool_free_res();
  4167. return ret;
  4168. }