wm_tool.c 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982
  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 % WM_TOOL_ONCE_READ_LEN != 0)
  2758. {
  2759. patch = WM_TOOL_ONCE_READ_LEN - readlen % WM_TOOL_ONCE_READ_LEN;
  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 % WM_TOOL_ONCE_READ_LEN != 0)
  2839. {
  2840. patch = WM_TOOL_ONCE_READ_LEN - readlen % WM_TOOL_ONCE_READ_LEN;
  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] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  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 (strstr(macstr, "Mac:"))
  3737. {
  3738. err = wm_tool_str_to_hex_array(macstr + strlen("MAC:"), 6, macaddr);
  3739. }
  3740. else
  3741. {
  3742. err = 0;
  3743. }
  3744. if (!err)
  3745. {
  3746. wm_tool_printf("mac %02X-%02X-%02X-%02X-%02X-%02X.\r\n", macaddr[0],
  3747. macaddr[1], macaddr[2], macaddr[3], macaddr[4], macaddr[5]);
  3748. if (!strncmp(macstr, "Mac:", strlen("Mac:")) &&
  3749. (WM_TOOL_DL_TYPE_FLS != wm_tool_dl_type) &&
  3750. !wm_tool_dl_erase)
  3751. {
  3752. wm_tool_printf("please download the firmware in .fls format.\r\n");
  3753. }
  3754. else
  3755. {
  3756. ret = 0;
  3757. }
  3758. }
  3759. break;
  3760. }
  3761. }
  3762. } while (err > 0);
  3763. }
  3764. wm_tool_uart_set_block(0);
  3765. return ret;
  3766. }
  3767. static int wm_tool_xmodem_download(const char *image)
  3768. {
  3769. FILE *imgfp;
  3770. unsigned char packet_data[XMODEM_DATA_SIZE];
  3771. unsigned char frame_data[XMODEM_DATA_SIZE + XMODEM_CRC_SIZE + XMODEM_FRAME_ID_SIZE + 1];
  3772. int complete, retry_num, pack_counter, read_number, write_number = 0, i;
  3773. unsigned short crc_value;
  3774. unsigned char ack_id;
  3775. int sndlen;
  3776. int ret = -111;
  3777. imgfp = fopen(image, "rb");
  3778. if (!imgfp)
  3779. {
  3780. wm_tool_printf("can not open image to download.\r\n");
  3781. return -1;
  3782. }
  3783. size_t fz = 0;
  3784. fseek(imgfp, 0L, SEEK_END);
  3785. fz = ftell(imgfp);
  3786. fseek(imgfp, 0L, SEEK_SET);
  3787. if (fz == 0) {
  3788. wm_tool_printf("image is emtry.\r\n");
  3789. return -1;
  3790. }
  3791. sndlen = 0;
  3792. pack_counter = 0;
  3793. complete = 0;
  3794. retry_num = 0;
  3795. wm_tool_printf("start download.\r\n");
  3796. wm_tool_printf("download 0%%\r\n");
  3797. wm_tool_uart_clear();
  3798. wm_tool_uart_set_block(1);
  3799. ack_id = XMODEM_ACK;
  3800. while (!complete)
  3801. {
  3802. WM_TOOL_DBG_PRINT("switch ack_id = %x\r\n", ack_id);
  3803. switch(ack_id)
  3804. {
  3805. case XMODEM_ACK:
  3806. {
  3807. retry_num = 0;
  3808. pack_counter++;
  3809. read_number = fread(packet_data, sizeof(char), XMODEM_DATA_SIZE, imgfp);
  3810. WM_TOOL_DBG_PRINT("fread = %d\r\n", read_number);
  3811. if (read_number > 0)
  3812. {
  3813. sndlen += read_number;
  3814. if (read_number < XMODEM_DATA_SIZE)
  3815. {
  3816. WM_TOOL_DBG_PRINT("start filling the last frame!\r\n");
  3817. for ( ; read_number < XMODEM_DATA_SIZE; read_number++)
  3818. packet_data[read_number] = 0x0;
  3819. }
  3820. frame_data[0] = XMODEM_HEAD;
  3821. frame_data[1] = (char)pack_counter;
  3822. frame_data[2] = (char)(255 - frame_data[1]);
  3823. for (i = 0; i < XMODEM_DATA_SIZE; i++)
  3824. frame_data[i + 3] = packet_data[i];
  3825. crc_value = wm_tool_get_crc16(packet_data, XMODEM_DATA_SIZE);
  3826. frame_data[XMODEM_DATA_SIZE + 3]=(unsigned char)(crc_value >> 8);
  3827. frame_data[XMODEM_DATA_SIZE + 4]=(unsigned char)(crc_value);
  3828. write_number = wm_tool_uart_write(frame_data, XMODEM_DATA_SIZE + 5);
  3829. if (write_number <= 0)
  3830. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3831. WM_TOOL_DBG_PRINT("waiting for ack, %d, %d ...\r\n", pack_counter, write_number);
  3832. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3833. if (ack_id == XMODEM_ACK)
  3834. {
  3835. WM_TOOL_DBG_PRINT("Ok!\r\n");
  3836. if (sndlen % 10240 == 0)
  3837. {
  3838. //wm_tool_printf("#");
  3839. wm_tool_printf("#download %d%%\r\n", sndlen >= fz ? 99 : sndlen / (fz));
  3840. }
  3841. }
  3842. else
  3843. {
  3844. WM_TOOL_DBG_PRINT("error = %x!\r\n", ack_id);
  3845. }
  3846. }
  3847. else
  3848. {
  3849. ack_id = XMODEM_EOT;
  3850. complete = 1;
  3851. WM_TOOL_DBG_PRINT("waiting for complete ack ...\r\n");
  3852. while (ack_id != XMODEM_ACK)
  3853. {
  3854. ack_id = XMODEM_EOT;
  3855. write_number = wm_tool_uart_write(&ack_id, 1);
  3856. if (write_number <= 0)
  3857. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3858. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3859. }
  3860. WM_TOOL_DBG_PRINT("ok\r\n");
  3861. wm_tool_printf("download 100%%\r\n");
  3862. //wm_tool_printf("download completed.\r\n");
  3863. ret = 0;
  3864. }
  3865. break;
  3866. }
  3867. case XMODEM_NAK:
  3868. {
  3869. if ( retry_num++ > 100)
  3870. {
  3871. WM_TOOL_DBG_PRINT("retry too many times, quit!\r\n");
  3872. wm_tool_printf("download firmware timeout.\r\n");
  3873. complete = 1;
  3874. }
  3875. else
  3876. {
  3877. write_number = wm_tool_uart_write(frame_data, XMODEM_DATA_SIZE + 5);
  3878. if (write_number <= 0)
  3879. wm_tool_printf("write serial error, errno = %d.\r\n", errno);
  3880. WM_TOOL_DBG_PRINT("retry for ack, %d, %d ...\r\n", pack_counter, write_number);
  3881. while ((wm_tool_uart_read(&ack_id, 1)) <= 0);
  3882. if (ack_id == XMODEM_ACK)
  3883. {
  3884. WM_TOOL_DBG_PRINT("ok\r\n");
  3885. }
  3886. else
  3887. {
  3888. WM_TOOL_DBG_PRINT("error!\r\n");
  3889. }
  3890. }
  3891. break;
  3892. }
  3893. default:
  3894. {
  3895. WM_TOOL_DBG_PRINT("fatal error!\r\n");
  3896. WM_TOOL_DBG_PRINT("unknown xmodem protocal [%x].\r\n", ack_id);
  3897. wm_tool_printf("\r\ndownload failed, please reset and try again.\r\n");
  3898. complete = 1;
  3899. break;
  3900. }
  3901. }
  3902. }
  3903. wm_tool_uart_set_block(0);
  3904. fclose(imgfp);
  3905. return ret;
  3906. }
  3907. static int wm_tool_download_firmware(void)
  3908. {
  3909. int ret;
  3910. int cnt = 0;
  3911. int note = 1;
  3912. int timeout = 0;
  3913. float timeuse;
  3914. time_t start, end;
  3915. unsigned char ch;
  3916. wm_tool_printf("connecting serial...\r\n");
  3917. ret = wm_tool_uart_open(wm_tool_serial_path);
  3918. if (ret)
  3919. {
  3920. wm_tool_printf("can not open serial\r\n");
  3921. return ret;
  3922. }
  3923. /* In some cases, setting the serial port initialization setting requires a delay. */
  3924. wm_tool_delay_ms(500);
  3925. wm_tool_printf("serial connected.\r\n");
  3926. if (WM_TOOL_DL_ACTION_AT == wm_tool_dl_action)
  3927. {
  3928. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_normal_serial_rate)
  3929. wm_tool_uart_set_speed(wm_tool_normal_serial_rate);
  3930. #if 0 /* use erase option */
  3931. if (WM_TOOL_DL_TYPE_FLS == wm_tool_dl_type)
  3932. {
  3933. ret = wm_tool_uart_write("AT+&FLSW=8002000,0\r\n", strlen("AT+&FLSW=8002000,0\r\n"));
  3934. if (ret <= 0)
  3935. {
  3936. wm_tool_printf("destroy secboot failed.\r\n");
  3937. wm_tool_uart_close();
  3938. return -3;
  3939. }
  3940. wm_tool_delay_ms(300);
  3941. }
  3942. #endif
  3943. ret = wm_tool_uart_write("AT+Z\r\n", strlen("AT+Z\r\n"));
  3944. if (ret <= 0)
  3945. {
  3946. wm_tool_printf("reset error.\r\n");
  3947. wm_tool_uart_close();
  3948. return -4;
  3949. }
  3950. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_normal_serial_rate)
  3951. wm_tool_uart_set_speed(WM_TOOL_DEFAULT_BAUD_RATE);
  3952. }
  3953. else if (WM_TOOL_DL_ACTION_RTS == wm_tool_dl_action)
  3954. {
  3955. ret = wm_tool_uart_set_dtr(0);
  3956. ret |= wm_tool_uart_set_rts(1);
  3957. wm_tool_delay_ms(50);
  3958. ret |= wm_tool_uart_set_dtr(1);
  3959. ret |= wm_tool_uart_set_rts(0);
  3960. wm_tool_delay_ms(50);
  3961. ret |= wm_tool_uart_set_dtr(0);
  3962. if (ret < 0)
  3963. {
  3964. wm_tool_printf("set rts to reboot error.\r\n");
  3965. wm_tool_uart_close();
  3966. return -5;
  3967. }
  3968. }
  3969. wm_tool_printf("wait serial sync...");
  3970. wm_tool_send_esc2uart(500);/* used for delay */
  3971. start = time(NULL);
  3972. do
  3973. {
  3974. ret = wm_tool_uart_read(&ch, 1);
  3975. WM_TOOL_DBG_PRINT("ret=%d, %x-%c\r\n", ret, ch, ch);
  3976. if (ret > 0)
  3977. {
  3978. if (('C' == ch) || ('P' == ch))
  3979. cnt++;
  3980. else
  3981. cnt = 0;
  3982. }
  3983. else
  3984. {
  3985. wm_tool_send_esc2uart(30);
  3986. }
  3987. end = time(NULL);
  3988. timeuse = difftime(end, start);
  3989. if (timeuse >= 1)
  3990. {
  3991. wm_tool_printf(".");
  3992. if ((((int)timeuse) % 2) == 0) {
  3993. wm_tool_uart_set_rts(0);
  3994. }
  3995. else {
  3996. wm_tool_uart_set_rts(1);
  3997. }
  3998. wm_tool_send_esc2uart(0);
  3999. timeout++;
  4000. if ((timeout >= (WM_TOOL_DOWNLOAD_TIMEOUT_SEC / 10)) && note)
  4001. {
  4002. wm_tool_printf("\r\nplease manually reset the device.\r\n");
  4003. note = 0;
  4004. }
  4005. else if (timeout > WM_TOOL_DOWNLOAD_TIMEOUT_SEC)
  4006. {
  4007. wm_tool_uart_close();
  4008. wm_tool_printf("\r\nserial sync timeout.\r\n");
  4009. return -6;
  4010. }
  4011. start = time(NULL);
  4012. }
  4013. } while (cnt < 3);
  4014. wm_tool_printf("\r\nserial sync sucess.\r\n");
  4015. // ret = wm_tool_query_mac();
  4016. // if (ret)
  4017. // {
  4018. // wm_tool_uart_close();
  4019. // wm_tool_printf("download failed.\r\n");
  4020. // return ret;
  4021. // }
  4022. if (WM_TOOL_DL_ERASE_ALL == wm_tool_dl_erase)
  4023. {
  4024. ret = wm_tool_erase_image(WM_TOOL_DL_ERASE_ALL);
  4025. if (ret)
  4026. {
  4027. wm_tool_uart_close();
  4028. wm_tool_printf("failed to erase.\r\n");
  4029. return ret;
  4030. }
  4031. }
  4032. if (!wm_tool_download_image && wm_tool_dl_erase)
  4033. {
  4034. return 0;
  4035. }
  4036. if (WM_TOOL_DEFAULT_BAUD_RATE != wm_tool_download_serial_rate)
  4037. {
  4038. ret = wm_tool_set_wifi_chip_speed(wm_tool_download_serial_rate);
  4039. if (ret > 0)
  4040. {
  4041. wm_tool_delay_ms(1 * 1000);
  4042. wm_tool_uart_set_speed(wm_tool_download_serial_rate);
  4043. }
  4044. }
  4045. ret = wm_tool_xmodem_download(wm_tool_download_image);
  4046. if (ret == 0) {
  4047. wm_tool_delay_ms(200);
  4048. // 21 06 00 c7 7c 3f 00 00 00
  4049. wm_tool_uart_write(wm_tool_chip_cmd_reset, sizeof(wm_tool_chip_cmd_reset));
  4050. //wm_tool_delay_ms(5);
  4051. wm_tool_printf("download completed.\r\n");
  4052. }
  4053. wm_tool_uart_close();
  4054. return ret;
  4055. }
  4056. static void wm_tool_show_local_com(void)
  4057. {
  4058. #if defined(__APPLE__) && defined(__MACH__)
  4059. char *comstr = "tty.usbserial";
  4060. #elif defined(__CYGWIN__)
  4061. int num;
  4062. char *comstr = "ttyS";
  4063. #elif defined(__linux__)
  4064. char *comstr = "ttyUSB";
  4065. #endif
  4066. #if defined(__APPLE__) || defined(__MACH__) || defined(__CYGWIN__) || defined(__linux__)
  4067. DIR *dir;
  4068. struct dirent *file;
  4069. dir = opendir("/dev");
  4070. if (dir)
  4071. {
  4072. while (NULL != (file = readdir(dir)))
  4073. {
  4074. if ((0 == strncmp(file->d_name, comstr, strlen(comstr))) && (DT_CHR == file->d_type))
  4075. {
  4076. #if defined(__CYGWIN__)
  4077. num = atoi(file->d_name + strlen(comstr));
  4078. wm_tool_printf("COM%d ", num + 1);
  4079. #else
  4080. wm_tool_printf("%s ", file->d_name);
  4081. #endif
  4082. }
  4083. }
  4084. closedir(dir);
  4085. wm_tool_printf("\r\n");
  4086. }
  4087. #elif defined(__MINGW32__)
  4088. LONG ret;
  4089. HKEY key;
  4090. DWORD i = 0;
  4091. DWORD knlen;
  4092. char kname[WM_TOOL_PATH_MAX] = {0};
  4093. DWORD kvlen;
  4094. char kvalue[WM_TOOL_PATH_MAX] = {0};
  4095. REGSAM kmask = KEY_READ;
  4096. #if defined(KEY_WOW64_64KEY)
  4097. BOOL is_64;
  4098. if (IsWow64Process(GetCurrentProcess(), &is_64))
  4099. {
  4100. if (is_64)
  4101. kmask |= KEY_WOW64_64KEY;
  4102. }
  4103. #endif
  4104. ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, NULL, 0, kmask, NULL, &key, NULL);
  4105. if (ret != ERROR_SUCCESS)
  4106. {
  4107. return;
  4108. }
  4109. do{
  4110. knlen = sizeof(kname);
  4111. kvlen = sizeof(kvalue);
  4112. ret = RegEnumValue(key, i, kname, &knlen, 0, NULL, (LPBYTE)kvalue, &kvlen);
  4113. if (ret == ERROR_SUCCESS)
  4114. {
  4115. if (strcmp(kvalue, "") != 0)
  4116. {
  4117. wm_tool_printf("%s ", kvalue);
  4118. }
  4119. }
  4120. i++;
  4121. } while (ret != ERROR_NO_MORE_ITEMS);
  4122. RegCloseKey(key);
  4123. wm_tool_printf("\r\n");
  4124. #else
  4125. wm_tool_printf("\r\nunsupported system.\r\n");
  4126. #endif
  4127. return;
  4128. }
  4129. static void wm_tool_free_res(void)
  4130. {
  4131. if (wm_tool_download_image)
  4132. free(wm_tool_download_image);
  4133. if (wm_tool_output_image)
  4134. free(wm_tool_output_image);
  4135. if (wm_tool_input_binary)
  4136. free(wm_tool_input_binary);
  4137. if (wm_tool_secboot_image)
  4138. free(wm_tool_secboot_image);
  4139. return;
  4140. }
  4141. int main(int argc, char *argv[])
  4142. {
  4143. int ret = 0;
  4144. if (!wm_tool_parse_arv(argc, argv))
  4145. {
  4146. wm_tool_print_usage(argv[0]);
  4147. wm_tool_free_res();
  4148. return 0;
  4149. }
  4150. if (wm_tool_show_usage)
  4151. {
  4152. wm_tool_print_usage(argv[0]);
  4153. wm_tool_free_res();
  4154. return 0;
  4155. }
  4156. if (wm_tool_show_ver)
  4157. {
  4158. wm_tool_print_version(argv[0]);
  4159. wm_tool_free_res();
  4160. return 0;
  4161. }
  4162. if (wm_tool_list_com)
  4163. {
  4164. wm_tool_show_local_com();
  4165. wm_tool_free_res();
  4166. return 0;
  4167. }
  4168. if (wm_tool_input_binary)
  4169. {
  4170. ret = wm_tool_pack_firmware();
  4171. }
  4172. if (wm_tool_download_image || wm_tool_dl_erase)
  4173. {
  4174. ret = wm_tool_download_firmware();
  4175. }
  4176. if (wm_tool_show_log_type)
  4177. {
  4178. ret = wm_tool_show_log_from_serial();
  4179. }
  4180. if (ret > 0)
  4181. wm_tool_print_usage(argv[0]);
  4182. wm_tool_free_res();
  4183. return ret;
  4184. }