wm_tool.c 141 KB

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