esptool_with_merge_bin.py 206 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422
  1. #!/usr/bin/env python
  2. #
  3. # ESP8266 & ESP32 family ROM Bootloader Utility
  4. # Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, Espressif Systems (Shanghai) PTE LTD, other contributors as noted.
  5. # https://github.com/espressif/esptool
  6. #
  7. # This program is free software; you can redistribute it and/or modify it under
  8. # the terms of the GNU General Public License as published by the Free Software
  9. # Foundation; either version 2 of the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along with
  16. # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  17. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. from __future__ import division, print_function
  19. import argparse
  20. import base64
  21. import binascii
  22. import copy
  23. import hashlib
  24. import inspect
  25. import io
  26. import itertools
  27. import os
  28. import shlex
  29. import string
  30. import struct
  31. import sys
  32. import time
  33. import zlib
  34. try:
  35. import serial
  36. except ImportError:
  37. print("Pyserial is not installed for %s. Check the README for installation instructions." % (sys.executable))
  38. raise
  39. # check 'serial' is 'pyserial' and not 'serial' https://github.com/espressif/esptool/issues/269
  40. try:
  41. if "serialization" in serial.__doc__ and "deserialization" in serial.__doc__:
  42. raise ImportError("""
  43. esptool.py depends on pyserial, but there is a conflict with a currently installed package named 'serial'.
  44. You may be able to work around this by 'pip uninstall serial; pip install pyserial' \
  45. but this may break other installed Python software that depends on 'serial'.
  46. There is no good fix for this right now, apart from configuring virtualenvs. \
  47. See https://github.com/espressif/esptool/issues/269#issuecomment-385298196 for discussion of the underlying issue(s).""")
  48. except TypeError:
  49. pass # __doc__ returns None for pyserial
  50. try:
  51. import serial.tools.list_ports as list_ports
  52. except ImportError:
  53. print("The installed version (%s) of pyserial appears to be too old for esptool.py (Python interpreter %s). "
  54. "Check the README for installation instructions." % (sys.VERSION, sys.executable))
  55. raise
  56. except Exception:
  57. if sys.platform == "darwin":
  58. # swallow the exception, this is a known issue in pyserial+macOS Big Sur preview ref https://github.com/espressif/esptool/issues/540
  59. list_ports = None
  60. else:
  61. raise
  62. __version__ = "3.1-dev"
  63. MAX_UINT32 = 0xffffffff
  64. MAX_UINT24 = 0xffffff
  65. DEFAULT_TIMEOUT = 3 # timeout for most flash operations
  66. START_FLASH_TIMEOUT = 20 # timeout for starting flash (may perform erase)
  67. CHIP_ERASE_TIMEOUT = 120 # timeout for full chip erase
  68. MAX_TIMEOUT = CHIP_ERASE_TIMEOUT * 2 # longest any command can run
  69. SYNC_TIMEOUT = 0.1 # timeout for syncing with bootloader
  70. MD5_TIMEOUT_PER_MB = 8 # timeout (per megabyte) for calculating md5sum
  71. ERASE_REGION_TIMEOUT_PER_MB = 30 # timeout (per megabyte) for erasing a region
  72. ERASE_WRITE_TIMEOUT_PER_MB = 40 # timeout (per megabyte) for erasing and writing data
  73. MEM_END_ROM_TIMEOUT = 0.05 # special short timeout for ESP_MEM_END, as it may never respond
  74. DEFAULT_SERIAL_WRITE_TIMEOUT = 10 # timeout for serial port write
  75. DEFAULT_CONNECT_ATTEMPTS = 7 # default number of times to try connection
  76. def timeout_per_mb(seconds_per_mb, size_bytes):
  77. """ Scales timeouts which are size-specific """
  78. result = seconds_per_mb * (size_bytes / 1e6)
  79. if result < DEFAULT_TIMEOUT:
  80. return DEFAULT_TIMEOUT
  81. return result
  82. def _chip_to_rom_loader(chip):
  83. return {
  84. 'esp8266': ESP8266ROM,
  85. 'esp32': ESP32ROM,
  86. 'esp32s2': ESP32S2ROM,
  87. 'esp32s3beta2': ESP32S3BETA2ROM,
  88. 'esp32s3beta3': ESP32S3BETA3ROM,
  89. 'esp32c3': ESP32C3ROM,
  90. }[chip]
  91. def get_default_connected_device(serial_list, port, connect_attempts, initial_baud, chip='auto', trace=False,
  92. before='default_reset'):
  93. _esp = None
  94. for each_port in reversed(serial_list):
  95. print("Serial port %s" % each_port)
  96. try:
  97. if chip == 'auto':
  98. _esp = ESPLoader.detect_chip(each_port, initial_baud, before, trace,
  99. connect_attempts)
  100. else:
  101. chip_class = _chip_to_rom_loader(chip)
  102. _esp = chip_class(each_port, initial_baud, trace)
  103. _esp.connect(before, connect_attempts)
  104. break
  105. except (FatalError, OSError) as err:
  106. if port is not None:
  107. raise
  108. print("%s failed to connect: %s" % (each_port, err))
  109. _esp = None
  110. return _esp
  111. DETECTED_FLASH_SIZES = {0x12: '256KB', 0x13: '512KB', 0x14: '1MB',
  112. 0x15: '2MB', 0x16: '4MB', 0x17: '8MB', 0x18: '16MB'}
  113. def check_supported_function(func, check_func):
  114. """
  115. Decorator implementation that wraps a check around an ESPLoader
  116. bootloader function to check if it's supported.
  117. This is used to capture the multidimensional differences in
  118. functionality between the ESP8266 & ESP32/32S2/32S3/32C3 ROM loaders, and the
  119. software stub that runs on both. Not possible to do this cleanly
  120. via inheritance alone.
  121. """
  122. def inner(*args, **kwargs):
  123. obj = args[0]
  124. if check_func(obj):
  125. return func(*args, **kwargs)
  126. else:
  127. raise NotImplementedInROMError(obj, func)
  128. return inner
  129. def stub_function_only(func):
  130. """ Attribute for a function only supported in the software stub loader """
  131. return check_supported_function(func, lambda o: o.IS_STUB)
  132. def stub_and_esp32_function_only(func):
  133. """ Attribute for a function only supported by software stubs or ESP32/32S2/32S3/32C3 ROM """
  134. return check_supported_function(func, lambda o: o.IS_STUB or isinstance(o, ESP32ROM))
  135. PYTHON2 = sys.version_info[0] < 3 # True if on pre-Python 3
  136. # Function to return nth byte of a bitstring
  137. # Different behaviour on Python 2 vs 3
  138. if PYTHON2:
  139. def byte(bitstr, index):
  140. return ord(bitstr[index])
  141. else:
  142. def byte(bitstr, index):
  143. return bitstr[index]
  144. # Provide a 'basestring' class on Python 3
  145. try:
  146. basestring
  147. except NameError:
  148. basestring = str
  149. def print_overwrite(message, last_line=False):
  150. """ Print a message, overwriting the currently printed line.
  151. If last_line is False, don't append a newline at the end (expecting another subsequent call will overwrite this one.)
  152. After a sequence of calls with last_line=False, call once with last_line=True.
  153. If output is not a TTY (for example redirected a pipe), no overwriting happens and this function is the same as print().
  154. """
  155. if sys.stdout.isatty():
  156. print("\r%s" % message, end='\n' if last_line else '')
  157. else:
  158. print(message)
  159. def _mask_to_shift(mask):
  160. """ Return the index of the least significant bit in the mask """
  161. shift = 0
  162. while mask & 0x1 == 0:
  163. shift += 1
  164. mask >>= 1
  165. return shift
  166. def esp8266_function_only(func):
  167. """ Attribute for a function only supported on ESP8266 """
  168. return check_supported_function(func, lambda o: o.CHIP_NAME == "ESP8266")
  169. class ESPLoader(object):
  170. """ Base class providing access to ESP ROM & software stub bootloaders.
  171. Subclasses provide ESP8266 & ESP32 specific functionality.
  172. Don't instantiate this base class directly, either instantiate a subclass or
  173. call ESPLoader.detect_chip() which will interrogate the chip and return the
  174. appropriate subclass instance.
  175. """
  176. CHIP_NAME = "Espressif device"
  177. IS_STUB = False
  178. DEFAULT_PORT = "/dev/ttyUSB0"
  179. # Commands supported by ESP8266 ROM bootloader
  180. ESP_FLASH_BEGIN = 0x02
  181. ESP_FLASH_DATA = 0x03
  182. ESP_FLASH_END = 0x04
  183. ESP_MEM_BEGIN = 0x05
  184. ESP_MEM_END = 0x06
  185. ESP_MEM_DATA = 0x07
  186. ESP_SYNC = 0x08
  187. ESP_WRITE_REG = 0x09
  188. ESP_READ_REG = 0x0a
  189. # Some comands supported by ESP32 ROM bootloader (or -8266 w/ stub)
  190. ESP_SPI_SET_PARAMS = 0x0B
  191. ESP_SPI_ATTACH = 0x0D
  192. ESP_READ_FLASH_SLOW = 0x0e # ROM only, much slower than the stub flash read
  193. ESP_CHANGE_BAUDRATE = 0x0F
  194. ESP_FLASH_DEFL_BEGIN = 0x10
  195. ESP_FLASH_DEFL_DATA = 0x11
  196. ESP_FLASH_DEFL_END = 0x12
  197. ESP_SPI_FLASH_MD5 = 0x13
  198. # Commands supported by ESP32-S2/S3/C3 ROM bootloader only
  199. ESP_GET_SECURITY_INFO = 0x14
  200. # Some commands supported by stub only
  201. ESP_ERASE_FLASH = 0xD0
  202. ESP_ERASE_REGION = 0xD1
  203. ESP_READ_FLASH = 0xD2
  204. ESP_RUN_USER_CODE = 0xD3
  205. # Flash encryption encrypted data command
  206. ESP_FLASH_ENCRYPT_DATA = 0xD4
  207. # Response code(s) sent by ROM
  208. ROM_INVALID_RECV_MSG = 0x05 # response if an invalid message is received
  209. # Maximum block sized for RAM and Flash writes, respectively.
  210. ESP_RAM_BLOCK = 0x1800
  211. FLASH_WRITE_SIZE = 0x400
  212. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  213. ESP_ROM_BAUD = 115200
  214. # First byte of the application image
  215. ESP_IMAGE_MAGIC = 0xe9
  216. # Initial state for the checksum routine
  217. ESP_CHECKSUM_MAGIC = 0xef
  218. # Flash sector size, minimum unit of erase.
  219. FLASH_SECTOR_SIZE = 0x1000
  220. UART_DATE_REG_ADDR = 0x60000078
  221. CHIP_DETECT_MAGIC_REG_ADDR = 0x40001000 # This ROM address has a different value on each chip model
  222. UART_CLKDIV_MASK = 0xFFFFF
  223. # Memory addresses
  224. IROM_MAP_START = 0x40200000
  225. IROM_MAP_END = 0x40300000
  226. # The number of bytes in the UART response that signify command status
  227. STATUS_BYTES_LENGTH = 2
  228. def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
  229. """Base constructor for ESPLoader bootloader interaction
  230. Don't call this constructor, either instantiate ESP8266ROM
  231. or ESP32ROM, or use ESPLoader.detect_chip().
  232. This base class has all of the instance methods for bootloader
  233. functionality supported across various chips & stub
  234. loaders. Subclasses replace the functions they don't support
  235. with ones which throw NotImplementedInROMError().
  236. """
  237. self.secure_download_mode = False # flag is set to True if esptool detects the ROM is in Secure Download Mode
  238. if isinstance(port, basestring):
  239. self._port = serial.serial_for_url(port)
  240. else:
  241. self._port = port
  242. self._slip_reader = slip_reader(self._port, self.trace)
  243. # setting baud rate in a separate step is a workaround for
  244. # CH341 driver on some Linux versions (this opens at 9600 then
  245. # sets), shouldn't matter for other platforms/drivers. See
  246. # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
  247. self._set_port_baudrate(baud)
  248. self._trace_enabled = trace_enabled
  249. # set write timeout, to prevent esptool blocked at write forever.
  250. try:
  251. self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
  252. except NotImplementedError:
  253. # no write timeout for RFC2217 ports
  254. # need to set the property back to None or it will continue to fail
  255. self._port.write_timeout = None
  256. @property
  257. def serial_port(self):
  258. return self._port.port
  259. def _set_port_baudrate(self, baud):
  260. try:
  261. self._port.baudrate = baud
  262. except IOError:
  263. raise FatalError("Failed to set baud rate %d. The driver may not support this rate." % baud)
  264. @staticmethod
  265. def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False,
  266. connect_attempts=DEFAULT_CONNECT_ATTEMPTS):
  267. """ Use serial access to detect the chip type.
  268. We use the UART's datecode register for this, it's mapped at
  269. the same address on ESP8266 & ESP32 so we can use one
  270. memory read and compare to the datecode register for each chip
  271. type.
  272. This routine automatically performs ESPLoader.connect() (passing
  273. connect_mode parameter) as part of querying the chip.
  274. """
  275. detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled)
  276. detect_port.connect(connect_mode, connect_attempts, detecting=True)
  277. try:
  278. print('Detecting chip type...', end='')
  279. sys.stdout.flush()
  280. chip_magic_value = detect_port.read_reg(ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR)
  281. for cls in [ESP8266ROM, ESP32ROM, ESP32S2ROM, ESP32S3BETA2ROM, ESP32S3BETA3ROM, ESP32C3ROM]:
  282. if chip_magic_value == cls.CHIP_DETECT_MAGIC_VALUE:
  283. # don't connect a second time
  284. inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
  285. inst._post_connect()
  286. print(' %s' % inst.CHIP_NAME, end='')
  287. return inst
  288. except UnsupportedCommandError:
  289. raise FatalError("Unsupported Command Error received. Probably this means Secure Download Mode is enabled, "
  290. "autodetection will not work. Need to manually specify the chip.")
  291. finally:
  292. print('') # end line
  293. raise FatalError("Unexpected CHIP magic value 0x%08x. Failed to autodetect chip type." % (chip_magic_value))
  294. """ Read a SLIP packet from the serial port """
  295. def read(self):
  296. return next(self._slip_reader)
  297. """ Write bytes to the serial port while performing SLIP escaping """
  298. def write(self, packet):
  299. buf = b'\xc0' \
  300. + (packet.replace(b'\xdb', b'\xdb\xdd').replace(b'\xc0', b'\xdb\xdc')) \
  301. + b'\xc0'
  302. self.trace("Write %d bytes: %s", len(buf), HexFormatter(buf))
  303. self._port.write(buf)
  304. def trace(self, message, *format_args):
  305. if self._trace_enabled:
  306. now = time.time()
  307. try:
  308. delta = now - self._last_trace
  309. except AttributeError:
  310. delta = 0.0
  311. self._last_trace = now
  312. prefix = "TRACE +%.3f " % delta
  313. print(prefix + (message % format_args))
  314. """ Calculate checksum of a blob, as it is defined by the ROM """
  315. @staticmethod
  316. def checksum(data, state=ESP_CHECKSUM_MAGIC):
  317. for b in data:
  318. if type(b) is int: # python 2/3 compat
  319. state ^= b
  320. else:
  321. state ^= ord(b)
  322. return state
  323. """ Send a request and read the response """
  324. def command(self, op=None, data=b"", chk=0, wait_response=True, timeout=DEFAULT_TIMEOUT):
  325. saved_timeout = self._port.timeout
  326. new_timeout = min(timeout, MAX_TIMEOUT)
  327. if new_timeout != saved_timeout:
  328. self._port.timeout = new_timeout
  329. try:
  330. if op is not None:
  331. self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%s",
  332. op, len(data), 1 if wait_response else 0, timeout, HexFormatter(data))
  333. pkt = struct.pack(b'<BBHI', 0x00, op, len(data), chk) + data
  334. self.write(pkt)
  335. if not wait_response:
  336. return
  337. self._port.flush()
  338. # tries to get a response until that response has the
  339. # same operation as the request or a retries limit has
  340. # exceeded. This is needed for some esp8266s that
  341. # reply with more sync responses than expected.
  342. for retry in range(100):
  343. p = self.read()
  344. if len(p) < 8:
  345. continue
  346. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
  347. if resp != 1:
  348. continue
  349. data = p[8:]
  350. if op is None or op_ret == op:
  351. return val, data
  352. if byte(data, 0) != 0 and byte(data, 1) == self.ROM_INVALID_RECV_MSG:
  353. self.flush_input() # Unsupported read_reg can result in more than one error response for some reason
  354. raise UnsupportedCommandError(self, op)
  355. finally:
  356. if new_timeout != saved_timeout:
  357. self._port.timeout = saved_timeout
  358. raise FatalError("Response doesn't match request")
  359. def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):
  360. """
  361. Execute a command with 'command', check the result code and throw an appropriate
  362. FatalError if it fails.
  363. Returns the "result" of a successful command.
  364. """
  365. val, data = self.command(op, data, chk, timeout=timeout)
  366. # things are a bit weird here, bear with us
  367. # the status bytes are the last 2/4 bytes in the data (depending on chip)
  368. if len(data) < self.STATUS_BYTES_LENGTH:
  369. raise FatalError("Failed to %s. Only got %d byte status response." % (op_description, len(data)))
  370. status_bytes = data[-self.STATUS_BYTES_LENGTH:]
  371. # we only care if the first one is non-zero. If it is, the second byte is a reason.
  372. if byte(status_bytes, 0) != 0:
  373. raise FatalError.WithResult('Failed to %s' % op_description, status_bytes)
  374. # if we had more data than just the status bytes, return it as the result
  375. # (this is used by the md5sum command, maybe other commands?)
  376. if len(data) > self.STATUS_BYTES_LENGTH:
  377. return data[:-self.STATUS_BYTES_LENGTH]
  378. else: # otherwise, just return the 'val' field which comes from the reply header (this is used by read_reg)
  379. return val
  380. def flush_input(self):
  381. self._port.flushInput()
  382. self._slip_reader = slip_reader(self._port, self.trace)
  383. def sync(self):
  384. self.command(self.ESP_SYNC, b'\x07\x07\x12\x20' + 32 * b'\x55',
  385. timeout=SYNC_TIMEOUT)
  386. for i in range(7):
  387. self.command()
  388. def _setDTR(self, state):
  389. self._port.setDTR(state)
  390. def _setRTS(self, state):
  391. self._port.setRTS(state)
  392. # Work-around for adapters on Windows using the usbser.sys driver:
  393. # generate a dummy change to DTR so that the set-control-line-state
  394. # request is sent with the updated RTS state and the same DTR state
  395. self._port.setDTR(self._port.dtr)
  396. def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
  397. """ A single connection attempt, with esp32r0 workaround options """
  398. # esp32r0_delay is a workaround for bugs with the most common auto reset
  399. # circuit and Windows, if the EN pin on the dev board does not have
  400. # enough capacitance.
  401. #
  402. # Newer dev boards shouldn't have this problem (higher value capacitor
  403. # on the EN pin), and ESP32 revision 1 can't use this workaround as it
  404. # relies on a silicon bug.
  405. #
  406. # Details: https://github.com/espressif/esptool/issues/136
  407. last_error = None
  408. # If we're doing no_sync, we're likely communicating as a pass through
  409. # with an intermediate device to the ESP32
  410. if mode == "no_reset_no_sync":
  411. return last_error
  412. # issue reset-to-bootloader:
  413. # RTS = either CH_PD/EN or nRESET (both active low = chip in reset
  414. # DTR = GPIO0 (active low = boot to flasher)
  415. #
  416. # DTR & RTS are active low signals,
  417. # ie True = pin @ 0V, False = pin @ VCC.
  418. if mode != 'no_reset':
  419. self._setDTR(False) # IO0=HIGH
  420. self._setRTS(True) # EN=LOW, chip in reset
  421. time.sleep(0.1)
  422. if esp32r0_delay:
  423. # Some chips are more likely to trigger the esp32r0
  424. # watchdog reset silicon bug if they're held with EN=LOW
  425. # for a longer period
  426. time.sleep(1.2)
  427. self._setDTR(True) # IO0=LOW
  428. self._setRTS(False) # EN=HIGH, chip out of reset
  429. if esp32r0_delay:
  430. # Sleep longer after reset.
  431. # This workaround only works on revision 0 ESP32 chips,
  432. # it exploits a silicon bug spurious watchdog reset.
  433. time.sleep(0.4) # allow watchdog reset to occur
  434. time.sleep(0.05)
  435. self._setDTR(False) # IO0=HIGH, done
  436. for _ in range(5):
  437. try:
  438. self.flush_input()
  439. self._port.flushOutput()
  440. self.sync()
  441. return None
  442. except FatalError as e:
  443. if esp32r0_delay:
  444. print('_', end='')
  445. else:
  446. print('.', end='')
  447. sys.stdout.flush()
  448. time.sleep(0.05)
  449. last_error = e
  450. return last_error
  451. def get_memory_region(self, name):
  452. """ Returns a tuple of (start, end) for the memory map entry with the given name, or None if it doesn't exist
  453. """
  454. try:
  455. return [(start, end) for (start, end, n) in self.MEMORY_MAP if n == name][0]
  456. except IndexError:
  457. return None
  458. def connect(self, mode='default_reset', attempts=DEFAULT_CONNECT_ATTEMPTS, detecting=False):
  459. """ Try connecting repeatedly until successful, or giving up """
  460. print('Connecting...', end='')
  461. sys.stdout.flush()
  462. last_error = None
  463. try:
  464. for _ in range(attempts) if attempts > 0 else itertools.count():
  465. last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)
  466. if last_error is None:
  467. break
  468. last_error = self._connect_attempt(mode=mode, esp32r0_delay=True)
  469. if last_error is None:
  470. break
  471. finally:
  472. print('') # end 'Connecting...' line
  473. if last_error is not None:
  474. raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
  475. if not detecting:
  476. try:
  477. # check the date code registers match what we expect to see
  478. chip_magic_value = self.read_reg(ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR)
  479. if chip_magic_value != self.CHIP_DETECT_MAGIC_VALUE:
  480. actually = None
  481. for cls in [ESP8266ROM, ESP32ROM, ESP32S2ROM, ESP32S3BETA2ROM, ESP32S3BETA3ROM, ESP32C3ROM]:
  482. if chip_magic_value == cls.CHIP_DETECT_MAGIC_VALUE:
  483. actually = cls
  484. break
  485. if actually is None:
  486. print(("WARNING: This chip doesn't appear to be a %s (chip magic value 0x%08x). "
  487. "Probably it is unsupported by this version of esptool.") % (self.CHIP_NAME, chip_magic_value))
  488. else:
  489. raise FatalError("This chip is %s not %s. Wrong --chip argument?" % (actually.CHIP_NAME, self.CHIP_NAME))
  490. except UnsupportedCommandError:
  491. self.secure_download_mode = True
  492. self._post_connect()
  493. def _post_connect(self):
  494. """
  495. Additional initialization hook, may be overridden by the chip-specific class.
  496. Gets called after connect, and after auto-detection.
  497. """
  498. pass
  499. def read_reg(self, addr, timeout=DEFAULT_TIMEOUT):
  500. """ Read memory address in target """
  501. # we don't call check_command here because read_reg() function is called
  502. # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
  503. # for different chip types (!)
  504. val, data = self.command(self.ESP_READ_REG, struct.pack('<I', addr), timeout=timeout)
  505. if byte(data, 0) != 0:
  506. raise FatalError.WithResult("Failed to read register address %08x" % addr, data)
  507. return val
  508. """ Write to memory address in target """
  509. def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0, delay_after_us=0):
  510. command = struct.pack('<IIII', addr, value, mask, delay_us)
  511. if delay_after_us > 0:
  512. # add a dummy write to a date register as an excuse to have a delay
  513. command += struct.pack('<IIII', self.UART_DATE_REG_ADDR, 0, 0, delay_after_us)
  514. return self.check_command("write target memory", self.ESP_WRITE_REG, command)
  515. def update_reg(self, addr, mask, new_val):
  516. """ Update register at 'addr', replace the bits masked out by 'mask'
  517. with new_val. new_val is shifted left to match the LSB of 'mask'
  518. Returns just-written value of register.
  519. """
  520. shift = _mask_to_shift(mask)
  521. val = self.read_reg(addr)
  522. val &= ~mask
  523. val |= (new_val << shift) & mask
  524. self.write_reg(addr, val)
  525. return val
  526. """ Start downloading an application image to RAM """
  527. def mem_begin(self, size, blocks, blocksize, offset):
  528. if self.IS_STUB: # check we're not going to overwrite a running stub with this data
  529. stub = self.STUB_CODE
  530. load_start = offset
  531. load_end = offset + size
  532. for (start, end) in [(stub["data_start"], stub["data_start"] + len(stub["data"])),
  533. (stub["text_start"], stub["text_start"] + len(stub["text"]))]:
  534. if load_start < end and load_end > start:
  535. raise FatalError(("Software loader is resident at 0x%08x-0x%08x. "
  536. "Can't load binary at overlapping address range 0x%08x-0x%08x. "
  537. "Either change binary loading address, or use the --no-stub "
  538. "option to disable the software loader.") % (start, end, load_start, load_end))
  539. return self.check_command("enter RAM download mode", self.ESP_MEM_BEGIN,
  540. struct.pack('<IIII', size, blocks, blocksize, offset))
  541. """ Send a block of an image to RAM """
  542. def mem_block(self, data, seq):
  543. return self.check_command("write to target RAM", self.ESP_MEM_DATA,
  544. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  545. self.checksum(data))
  546. """ Leave download mode and run the application """
  547. def mem_finish(self, entrypoint=0):
  548. # Sending ESP_MEM_END usually sends a correct response back, however sometimes
  549. # (with ROM loader) the executed code may reset the UART or change the baud rate
  550. # before the transmit FIFO is empty. So in these cases we set a short timeout and
  551. # ignore errors.
  552. timeout = DEFAULT_TIMEOUT if self.IS_STUB else MEM_END_ROM_TIMEOUT
  553. data = struct.pack('<II', int(entrypoint == 0), entrypoint)
  554. try:
  555. return self.check_command("leave RAM download mode", self.ESP_MEM_END,
  556. data=data, timeout=timeout)
  557. except FatalError:
  558. if self.IS_STUB:
  559. raise
  560. pass
  561. """ Start downloading to Flash (performs an erase)
  562. Returns number of blocks (of size self.FLASH_WRITE_SIZE) to write.
  563. """
  564. def flash_begin(self, size, offset, begin_rom_encrypted=False):
  565. num_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  566. erase_size = self.get_erase_size(offset, size)
  567. t = time.time()
  568. if self.IS_STUB:
  569. timeout = DEFAULT_TIMEOUT
  570. else:
  571. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, size) # ROM performs the erase up front
  572. params = struct.pack('<IIII', erase_size, num_blocks, self.FLASH_WRITE_SIZE, offset)
  573. if isinstance(self, (ESP32S2ROM, ESP32S3BETA2ROM, ESP32S3BETA3ROM, ESP32C3ROM)) and not self.IS_STUB:
  574. params += struct.pack('<I', 1 if begin_rom_encrypted else 0)
  575. self.check_command("enter Flash download mode", self.ESP_FLASH_BEGIN,
  576. params, timeout=timeout)
  577. if size != 0 and not self.IS_STUB:
  578. print("Took %.2fs to erase flash block" % (time.time() - t))
  579. return num_blocks
  580. """ Write block to flash """
  581. def flash_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
  582. self.check_command("write to target Flash after seq %d" % seq,
  583. self.ESP_FLASH_DATA,
  584. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  585. self.checksum(data),
  586. timeout=timeout)
  587. """ Encrypt before writing to flash """
  588. def flash_encrypt_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
  589. if isinstance(self, (ESP32S2ROM, ESP32C3ROM)) and not self.IS_STUB:
  590. # ROM support performs the encrypted writes via the normal write command,
  591. # triggered by flash_begin(begin_rom_encrypted=True)
  592. return self.flash_block(data, seq, timeout)
  593. self.check_command("Write encrypted to target Flash after seq %d" % seq,
  594. self.ESP_FLASH_ENCRYPT_DATA,
  595. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  596. self.checksum(data),
  597. timeout=timeout)
  598. """ Leave flash mode and run/reboot """
  599. def flash_finish(self, reboot=False):
  600. pkt = struct.pack('<I', int(not reboot))
  601. # stub sends a reply to this command
  602. self.check_command("leave Flash mode", self.ESP_FLASH_END, pkt)
  603. """ Run application code in flash """
  604. def run(self, reboot=False):
  605. # Fake flash begin immediately followed by flash end
  606. self.flash_begin(0, 0)
  607. self.flash_finish(reboot)
  608. """ Read SPI flash manufacturer and device id """
  609. def flash_id(self):
  610. SPIFLASH_RDID = 0x9F
  611. return self.run_spiflash_command(SPIFLASH_RDID, b"", 24)
  612. def get_security_info(self):
  613. # TODO: this only works on the ESP32S2 ROM code loader and needs to work in stub loader also
  614. res = self.check_command('get security info', self.ESP_GET_SECURITY_INFO, b'')
  615. res = struct.unpack("<IBBBBBBBB", res)
  616. flags, flash_crypt_cnt, key_purposes = res[0], res[1], res[2:]
  617. # TODO: pack this as some kind of better data type
  618. return (flags, flash_crypt_cnt, key_purposes)
  619. @classmethod
  620. def parse_flash_size_arg(cls, arg):
  621. try:
  622. return cls.FLASH_SIZES[arg]
  623. except KeyError:
  624. raise FatalError("Flash size '%s' is not supported by this chip type. Supported sizes: %s"
  625. % (arg, ", ".join(cls.FLASH_SIZES.keys())))
  626. def run_stub(self, stub=None):
  627. if stub is None:
  628. if self.IS_STUB:
  629. raise FatalError("Not possible for a stub to load another stub (memory likely to overlap.)")
  630. stub = self.STUB_CODE
  631. # Upload
  632. print("Uploading stub...")
  633. for field in ['text', 'data']:
  634. if field in stub:
  635. offs = stub[field + "_start"]
  636. length = len(stub[field])
  637. blocks = (length + self.ESP_RAM_BLOCK - 1) // self.ESP_RAM_BLOCK
  638. self.mem_begin(length, blocks, self.ESP_RAM_BLOCK, offs)
  639. for seq in range(blocks):
  640. from_offs = seq * self.ESP_RAM_BLOCK
  641. to_offs = from_offs + self.ESP_RAM_BLOCK
  642. self.mem_block(stub[field][from_offs:to_offs], seq)
  643. print("Running stub...")
  644. self.mem_finish(stub['entry'])
  645. p = self.read()
  646. if p != b'OHAI':
  647. raise FatalError("Failed to start stub. Unexpected response: %s" % p)
  648. print("Stub running...")
  649. return self.STUB_CLASS(self)
  650. @stub_and_esp32_function_only
  651. def flash_defl_begin(self, size, compsize, offset):
  652. """ Start downloading compressed data to Flash (performs an erase)
  653. Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
  654. """
  655. num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  656. erase_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  657. t = time.time()
  658. if self.IS_STUB:
  659. write_size = size # stub expects number of bytes here, manages erasing internally
  660. timeout = DEFAULT_TIMEOUT
  661. else:
  662. write_size = erase_blocks * self.FLASH_WRITE_SIZE # ROM expects rounded up to erase block size
  663. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, write_size) # ROM performs the erase up front
  664. print("Compressed %d bytes to %d..." % (size, compsize))
  665. params = struct.pack('<IIII', write_size, num_blocks, self.FLASH_WRITE_SIZE, offset)
  666. if isinstance(self, (ESP32S2ROM, ESP32S3BETA2ROM, ESP32S3BETA3ROM, ESP32C3ROM)) and not self.IS_STUB:
  667. params += struct.pack('<I', 0) # extra param is to enter encrypted flash mode via ROM (not supported currently)
  668. self.check_command("enter compressed flash mode", self.ESP_FLASH_DEFL_BEGIN, params, timeout=timeout)
  669. if size != 0 and not self.IS_STUB:
  670. # (stub erases as it writes, but ROM loaders erase on begin)
  671. print("Took %.2fs to erase flash block" % (time.time() - t))
  672. return num_blocks
  673. """ Write block to flash, send compressed """
  674. @stub_and_esp32_function_only
  675. def flash_defl_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
  676. self.check_command("write compressed data to flash after seq %d" % seq,
  677. self.ESP_FLASH_DEFL_DATA, struct.pack('<IIII', len(data), seq, 0, 0) + data, self.checksum(data), timeout=timeout)
  678. """ Leave compressed flash mode and run/reboot """
  679. @stub_and_esp32_function_only
  680. def flash_defl_finish(self, reboot=False):
  681. if not reboot and not self.IS_STUB:
  682. # skip sending flash_finish to ROM loader, as this
  683. # exits the bootloader. Stub doesn't do this.
  684. return
  685. pkt = struct.pack('<I', int(not reboot))
  686. self.check_command("leave compressed flash mode", self.ESP_FLASH_DEFL_END, pkt)
  687. self.in_bootloader = False
  688. @stub_and_esp32_function_only
  689. def flash_md5sum(self, addr, size):
  690. # the MD5 command returns additional bytes in the standard
  691. # command reply slot
  692. timeout = timeout_per_mb(MD5_TIMEOUT_PER_MB, size)
  693. res = self.check_command('calculate md5sum', self.ESP_SPI_FLASH_MD5, struct.pack('<IIII', addr, size, 0, 0),
  694. timeout=timeout)
  695. if len(res) == 32:
  696. return res.decode("utf-8") # already hex formatted
  697. elif len(res) == 16:
  698. return hexify(res).lower()
  699. else:
  700. raise FatalError("MD5Sum command returned unexpected result: %r" % res)
  701. @stub_and_esp32_function_only
  702. def change_baud(self, baud):
  703. print("Changing baud rate to %d" % baud)
  704. # stub takes the new baud rate and the old one
  705. second_arg = self._port.baudrate if self.IS_STUB else 0
  706. self.command(self.ESP_CHANGE_BAUDRATE, struct.pack('<II', baud, second_arg))
  707. print("Changed.")
  708. self._set_port_baudrate(baud)
  709. time.sleep(0.05) # get rid of crap sent during baud rate change
  710. self.flush_input()
  711. @stub_function_only
  712. def erase_flash(self):
  713. # depending on flash chip model the erase may take this long (maybe longer!)
  714. self.check_command("erase flash", self.ESP_ERASE_FLASH,
  715. timeout=CHIP_ERASE_TIMEOUT)
  716. @stub_function_only
  717. def erase_region(self, offset, size):
  718. if offset % self.FLASH_SECTOR_SIZE != 0:
  719. raise FatalError("Offset to erase from must be a multiple of 4096")
  720. if size % self.FLASH_SECTOR_SIZE != 0:
  721. raise FatalError("Size of data to erase must be a multiple of 4096")
  722. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, size)
  723. self.check_command("erase region", self.ESP_ERASE_REGION, struct.pack('<II', offset, size), timeout=timeout)
  724. def read_flash_slow(self, offset, length, progress_fn):
  725. raise NotImplementedInROMError(self, self.read_flash_slow)
  726. def read_flash(self, offset, length, progress_fn=None):
  727. if not self.IS_STUB:
  728. return self.read_flash_slow(offset, length, progress_fn) # ROM-only routine
  729. # issue a standard bootloader command to trigger the read
  730. self.check_command("read flash", self.ESP_READ_FLASH,
  731. struct.pack('<IIII',
  732. offset,
  733. length,
  734. self.FLASH_SECTOR_SIZE,
  735. 64))
  736. # now we expect (length // block_size) SLIP frames with the data
  737. data = b''
  738. while len(data) < length:
  739. p = self.read()
  740. data += p
  741. if len(data) < length and len(p) < self.FLASH_SECTOR_SIZE:
  742. raise FatalError('Corrupt data, expected 0x%x bytes but received 0x%x bytes' % (self.FLASH_SECTOR_SIZE, len(p)))
  743. self.write(struct.pack('<I', len(data)))
  744. if progress_fn and (len(data) % 1024 == 0 or len(data) == length):
  745. progress_fn(len(data), length)
  746. if progress_fn:
  747. progress_fn(len(data), length)
  748. if len(data) > length:
  749. raise FatalError('Read more than expected')
  750. digest_frame = self.read()
  751. if len(digest_frame) != 16:
  752. raise FatalError('Expected digest, got: %s' % hexify(digest_frame))
  753. expected_digest = hexify(digest_frame).upper()
  754. digest = hashlib.md5(data).hexdigest().upper()
  755. if digest != expected_digest:
  756. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  757. return data
  758. def flash_spi_attach(self, hspi_arg):
  759. """Send SPI attach command to enable the SPI flash pins
  760. ESP8266 ROM does this when you send flash_begin, ESP32 ROM
  761. has it as a SPI command.
  762. """
  763. # last 3 bytes in ESP_SPI_ATTACH argument are reserved values
  764. arg = struct.pack('<I', hspi_arg)
  765. if not self.IS_STUB:
  766. # ESP32 ROM loader takes additional 'is legacy' arg, which is not
  767. # currently supported in the stub loader or esptool.py (as it's not usually needed.)
  768. is_legacy = 0
  769. arg += struct.pack('BBBB', is_legacy, 0, 0, 0)
  770. self.check_command("configure SPI flash pins", ESP32ROM.ESP_SPI_ATTACH, arg)
  771. def flash_set_parameters(self, size):
  772. """Tell the ESP bootloader the parameters of the chip
  773. Corresponds to the "flashchip" data structure that the ROM
  774. has in RAM.
  775. 'size' is in bytes.
  776. All other flash parameters are currently hardcoded (on ESP8266
  777. these are mostly ignored by ROM code, on ESP32 I'm not sure.)
  778. """
  779. fl_id = 0
  780. total_size = size
  781. block_size = 64 * 1024
  782. sector_size = 4 * 1024
  783. page_size = 256
  784. status_mask = 0xffff
  785. self.check_command("set SPI params", ESP32ROM.ESP_SPI_SET_PARAMS,
  786. struct.pack('<IIIIII', fl_id, total_size, block_size, sector_size, page_size, status_mask))
  787. def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
  788. """Run an arbitrary SPI flash command.
  789. This function uses the "USR_COMMAND" functionality in the ESP
  790. SPI hardware, rather than the precanned commands supported by
  791. hardware. So the value of spiflash_command is an actual command
  792. byte, sent over the wire.
  793. After writing command byte, writes 'data' to MOSI and then
  794. reads back 'read_bits' of reply on MISO. Result is a number.
  795. """
  796. # SPI_USR register flags
  797. SPI_USR_COMMAND = (1 << 31)
  798. SPI_USR_MISO = (1 << 28)
  799. SPI_USR_MOSI = (1 << 27)
  800. # SPI registers, base address differs ESP32* vs 8266
  801. base = self.SPI_REG_BASE
  802. SPI_CMD_REG = base + 0x00
  803. SPI_USR_REG = base + self.SPI_USR_OFFS
  804. SPI_USR1_REG = base + self.SPI_USR1_OFFS
  805. SPI_USR2_REG = base + self.SPI_USR2_OFFS
  806. SPI_W0_REG = base + self.SPI_W0_OFFS
  807. # following two registers are ESP32 & 32S2/32C3 only
  808. if self.SPI_MOSI_DLEN_OFFS is not None:
  809. # ESP32/32S2/32C3 has a more sophisticated way to set up "user" commands
  810. def set_data_lengths(mosi_bits, miso_bits):
  811. SPI_MOSI_DLEN_REG = base + self.SPI_MOSI_DLEN_OFFS
  812. SPI_MISO_DLEN_REG = base + self.SPI_MISO_DLEN_OFFS
  813. if mosi_bits > 0:
  814. self.write_reg(SPI_MOSI_DLEN_REG, mosi_bits - 1)
  815. if miso_bits > 0:
  816. self.write_reg(SPI_MISO_DLEN_REG, miso_bits - 1)
  817. else:
  818. def set_data_lengths(mosi_bits, miso_bits):
  819. SPI_DATA_LEN_REG = SPI_USR1_REG
  820. SPI_MOSI_BITLEN_S = 17
  821. SPI_MISO_BITLEN_S = 8
  822. mosi_mask = 0 if (mosi_bits == 0) else (mosi_bits - 1)
  823. miso_mask = 0 if (miso_bits == 0) else (miso_bits - 1)
  824. self.write_reg(SPI_DATA_LEN_REG,
  825. (miso_mask << SPI_MISO_BITLEN_S) | (
  826. mosi_mask << SPI_MOSI_BITLEN_S))
  827. # SPI peripheral "command" bitmasks for SPI_CMD_REG
  828. SPI_CMD_USR = (1 << 18)
  829. # shift values
  830. SPI_USR2_COMMAND_LEN_SHIFT = 28
  831. if read_bits > 32:
  832. raise FatalError("Reading more than 32 bits back from a SPI flash operation is unsupported")
  833. if len(data) > 64:
  834. raise FatalError("Writing more than 64 bytes of data with one SPI command is unsupported")
  835. data_bits = len(data) * 8
  836. old_spi_usr = self.read_reg(SPI_USR_REG)
  837. old_spi_usr2 = self.read_reg(SPI_USR2_REG)
  838. flags = SPI_USR_COMMAND
  839. if read_bits > 0:
  840. flags |= SPI_USR_MISO
  841. if data_bits > 0:
  842. flags |= SPI_USR_MOSI
  843. set_data_lengths(data_bits, read_bits)
  844. self.write_reg(SPI_USR_REG, flags)
  845. self.write_reg(SPI_USR2_REG,
  846. (7 << SPI_USR2_COMMAND_LEN_SHIFT) | spiflash_command)
  847. if data_bits == 0:
  848. self.write_reg(SPI_W0_REG, 0) # clear data register before we read it
  849. else:
  850. data = pad_to(data, 4, b'\00') # pad to 32-bit multiple
  851. words = struct.unpack("I" * (len(data) // 4), data)
  852. next_reg = SPI_W0_REG
  853. for word in words:
  854. self.write_reg(next_reg, word)
  855. next_reg += 4
  856. self.write_reg(SPI_CMD_REG, SPI_CMD_USR)
  857. def wait_done():
  858. for _ in range(10):
  859. if (self.read_reg(SPI_CMD_REG) & SPI_CMD_USR) == 0:
  860. return
  861. raise FatalError("SPI command did not complete in time")
  862. wait_done()
  863. status = self.read_reg(SPI_W0_REG)
  864. # restore some SPI controller registers
  865. self.write_reg(SPI_USR_REG, old_spi_usr)
  866. self.write_reg(SPI_USR2_REG, old_spi_usr2)
  867. return status
  868. def read_status(self, num_bytes=2):
  869. """Read up to 24 bits (num_bytes) of SPI flash status register contents
  870. via RDSR, RDSR2, RDSR3 commands
  871. Not all SPI flash supports all three commands. The upper 1 or 2
  872. bytes may be 0xFF.
  873. """
  874. SPIFLASH_RDSR = 0x05
  875. SPIFLASH_RDSR2 = 0x35
  876. SPIFLASH_RDSR3 = 0x15
  877. status = 0
  878. shift = 0
  879. for cmd in [SPIFLASH_RDSR, SPIFLASH_RDSR2, SPIFLASH_RDSR3][0:num_bytes]:
  880. status += self.run_spiflash_command(cmd, read_bits=8) << shift
  881. shift += 8
  882. return status
  883. def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
  884. """Write up to 24 bits (num_bytes) of new status register
  885. num_bytes can be 1, 2 or 3.
  886. Not all flash supports the additional commands to write the
  887. second and third byte of the status register. When writing 2
  888. bytes, esptool also sends a 16-byte WRSR command (as some
  889. flash types use this instead of WRSR2.)
  890. If the set_non_volatile flag is set, non-volatile bits will
  891. be set as well as volatile ones (WREN used instead of WEVSR).
  892. """
  893. SPIFLASH_WRSR = 0x01
  894. SPIFLASH_WRSR2 = 0x31
  895. SPIFLASH_WRSR3 = 0x11
  896. SPIFLASH_WEVSR = 0x50
  897. SPIFLASH_WREN = 0x06
  898. SPIFLASH_WRDI = 0x04
  899. enable_cmd = SPIFLASH_WREN if set_non_volatile else SPIFLASH_WEVSR
  900. # try using a 16-bit WRSR (not supported by all chips)
  901. # this may be redundant, but shouldn't hurt
  902. if num_bytes == 2:
  903. self.run_spiflash_command(enable_cmd)
  904. self.run_spiflash_command(SPIFLASH_WRSR, struct.pack("<H", new_status))
  905. # also try using individual commands (also not supported by all chips for num_bytes 2 & 3)
  906. for cmd in [SPIFLASH_WRSR, SPIFLASH_WRSR2, SPIFLASH_WRSR3][0:num_bytes]:
  907. self.run_spiflash_command(enable_cmd)
  908. self.run_spiflash_command(cmd, struct.pack("B", new_status & 0xFF))
  909. new_status >>= 8
  910. self.run_spiflash_command(SPIFLASH_WRDI)
  911. def get_crystal_freq(self):
  912. # Figure out the crystal frequency from the UART clock divider
  913. # Returns a normalized value in integer MHz (40 or 26 are the only supported values)
  914. #
  915. # The logic here is:
  916. # - We know that our baud rate and the ESP UART baud rate are roughly the same, or we couldn't communicate
  917. # - We can read the UART clock divider register to know how the ESP derives this from the APB bus frequency
  918. # - Multiplying these two together gives us the bus frequency which is either the crystal frequency (ESP32)
  919. # or double the crystal frequency (ESP8266). See the self.XTAL_CLK_DIVIDER parameter for this factor.
  920. uart_div = self.read_reg(self.UART_CLKDIV_REG) & self.UART_CLKDIV_MASK
  921. est_xtal = (self._port.baudrate * uart_div) / 1e6 / self.XTAL_CLK_DIVIDER
  922. norm_xtal = 40 if est_xtal > 33 else 26
  923. if abs(norm_xtal - est_xtal) > 1:
  924. print("WARNING: Detected crystal freq %.2fMHz is quite different to normalized freq %dMHz. Unsupported crystal in use?" % (est_xtal, norm_xtal))
  925. return norm_xtal
  926. def hard_reset(self):
  927. self._setRTS(True) # EN->LOW
  928. time.sleep(0.1)
  929. self._setRTS(False)
  930. def soft_reset(self, stay_in_bootloader):
  931. if not self.IS_STUB:
  932. if stay_in_bootloader:
  933. return # ROM bootloader is already in bootloader!
  934. else:
  935. # 'run user code' is as close to a soft reset as we can do
  936. self.flash_begin(0, 0)
  937. self.flash_finish(False)
  938. else:
  939. if stay_in_bootloader:
  940. # soft resetting from the stub loader
  941. # will re-load the ROM bootloader
  942. self.flash_begin(0, 0)
  943. self.flash_finish(True)
  944. elif self.CHIP_NAME != "ESP8266":
  945. raise FatalError("Soft resetting is currently only supported on ESP8266")
  946. else:
  947. # running user code from stub loader requires some hacks
  948. # in the stub loader
  949. self.command(self.ESP_RUN_USER_CODE, wait_response=False)
  950. class ESP8266ROM(ESPLoader):
  951. """ Access class for ESP8266 ROM bootloader
  952. """
  953. CHIP_NAME = "ESP8266"
  954. IS_STUB = False
  955. CHIP_DETECT_MAGIC_VALUE = 0xfff0c101
  956. # OTP ROM addresses
  957. ESP_OTP_MAC0 = 0x3ff00050
  958. ESP_OTP_MAC1 = 0x3ff00054
  959. ESP_OTP_MAC3 = 0x3ff0005c
  960. SPI_REG_BASE = 0x60000200
  961. SPI_USR_OFFS = 0x1c
  962. SPI_USR1_OFFS = 0x20
  963. SPI_USR2_OFFS = 0x24
  964. SPI_MOSI_DLEN_OFFS = None
  965. SPI_MISO_DLEN_OFFS = None
  966. SPI_W0_OFFS = 0x40
  967. UART_CLKDIV_REG = 0x60000014
  968. XTAL_CLK_DIVIDER = 2
  969. FLASH_SIZES = {
  970. '512KB': 0x00,
  971. '256KB': 0x10,
  972. '1MB': 0x20,
  973. '2MB': 0x30,
  974. '4MB': 0x40,
  975. '2MB-c1': 0x50,
  976. '4MB-c1': 0x60,
  977. '8MB': 0x80,
  978. '16MB': 0x90,
  979. }
  980. BOOTLOADER_FLASH_OFFSET = 0
  981. MEMORY_MAP = [[0x3FF00000, 0x3FF00010, "DPORT"],
  982. [0x3FFE8000, 0x40000000, "DRAM"],
  983. [0x40100000, 0x40108000, "IRAM"],
  984. [0x40201010, 0x402E1010, "IROM"]]
  985. def get_efuses(self):
  986. # Return the 128 bits of ESP8266 efuse as a single Python integer
  987. result = self.read_reg(0x3ff0005c) << 96
  988. result |= self.read_reg(0x3ff00058) << 64
  989. result |= self.read_reg(0x3ff00054) << 32
  990. result |= self.read_reg(0x3ff00050)
  991. return result
  992. def _get_flash_size(self, efuses):
  993. # rX_Y = EFUSE_DATA_OUTX[Y]
  994. r0_4 = (efuses & (1 << 4)) != 0
  995. r3_25 = (efuses & (1 << 121)) != 0
  996. r3_26 = (efuses & (1 << 122)) != 0
  997. r3_27 = (efuses & (1 << 123)) != 0
  998. if r0_4 and not r3_25:
  999. if not r3_27 and not r3_26:
  1000. return 1
  1001. elif not r3_27 and r3_26:
  1002. return 2
  1003. if not r0_4 and r3_25:
  1004. if not r3_27 and not r3_26:
  1005. return 2
  1006. elif not r3_27 and r3_26:
  1007. return 4
  1008. return -1
  1009. def get_chip_description(self):
  1010. efuses = self.get_efuses()
  1011. is_8285 = (efuses & ((1 << 4) | 1 << 80)) != 0 # One or the other efuse bit is set for ESP8285
  1012. if is_8285:
  1013. flash_size = self._get_flash_size(efuses)
  1014. max_temp = (efuses & (1 << 5)) != 0 # This efuse bit identifies the max flash temperature
  1015. chip_name = {
  1016. 1: "ESP8285H08" if max_temp else "ESP8285N08",
  1017. 2: "ESP8285H16" if max_temp else "ESP8285N16"
  1018. }.get(flash_size, "ESP8285")
  1019. return chip_name
  1020. return "ESP8266EX"
  1021. def get_chip_features(self):
  1022. features = ["WiFi"]
  1023. if "ESP8285" in self.get_chip_description():
  1024. features += ["Embedded Flash"]
  1025. return features
  1026. def flash_spi_attach(self, hspi_arg):
  1027. if self.IS_STUB:
  1028. super(ESP8266ROM, self).flash_spi_attach(hspi_arg)
  1029. else:
  1030. # ESP8266 ROM has no flash_spi_attach command in serial protocol,
  1031. # but flash_begin will do it
  1032. self.flash_begin(0, 0)
  1033. def flash_set_parameters(self, size):
  1034. # not implemented in ROM, but OK to silently skip for ROM
  1035. if self.IS_STUB:
  1036. super(ESP8266ROM, self).flash_set_parameters(size)
  1037. def chip_id(self):
  1038. """ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """
  1039. id0 = self.read_reg(self.ESP_OTP_MAC0)
  1040. id1 = self.read_reg(self.ESP_OTP_MAC1)
  1041. return (id0 >> 24) | ((id1 & MAX_UINT24) << 8)
  1042. def read_mac(self):
  1043. """ Read MAC from OTP ROM """
  1044. mac0 = self.read_reg(self.ESP_OTP_MAC0)
  1045. mac1 = self.read_reg(self.ESP_OTP_MAC1)
  1046. mac3 = self.read_reg(self.ESP_OTP_MAC3)
  1047. if (mac3 != 0):
  1048. oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
  1049. elif ((mac1 >> 16) & 0xff) == 0:
  1050. oui = (0x18, 0xfe, 0x34)
  1051. elif ((mac1 >> 16) & 0xff) == 1:
  1052. oui = (0xac, 0xd0, 0x74)
  1053. else:
  1054. raise FatalError("Unknown OUI")
  1055. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  1056. def get_erase_size(self, offset, size):
  1057. """ Calculate an erase size given a specific size in bytes.
  1058. Provides a workaround for the bootloader erase bug."""
  1059. sectors_per_block = 16
  1060. sector_size = self.FLASH_SECTOR_SIZE
  1061. num_sectors = (size + sector_size - 1) // sector_size
  1062. start_sector = offset // sector_size
  1063. head_sectors = sectors_per_block - (start_sector % sectors_per_block)
  1064. if num_sectors < head_sectors:
  1065. head_sectors = num_sectors
  1066. if num_sectors < 2 * head_sectors:
  1067. return (num_sectors + 1) // 2 * sector_size
  1068. else:
  1069. return (num_sectors - head_sectors) * sector_size
  1070. def override_vddsdio(self, new_voltage):
  1071. raise NotImplementedInROMError("Overriding VDDSDIO setting only applies to ESP32")
  1072. class ESP8266StubLoader(ESP8266ROM):
  1073. """ Access class for ESP8266 stub loader, runs on top of ROM.
  1074. """
  1075. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1076. IS_STUB = True
  1077. def __init__(self, rom_loader):
  1078. self.secure_download_mode = rom_loader.secure_download_mode
  1079. self._port = rom_loader._port
  1080. self._trace_enabled = rom_loader._trace_enabled
  1081. self.flush_input() # resets _slip_reader
  1082. def get_erase_size(self, offset, size):
  1083. return size # stub doesn't have same size bug as ROM loader
  1084. ESP8266ROM.STUB_CLASS = ESP8266StubLoader
  1085. class ESP32ROM(ESPLoader):
  1086. """Access class for ESP32 ROM bootloader
  1087. """
  1088. CHIP_NAME = "ESP32"
  1089. IMAGE_CHIP_ID = 0
  1090. IS_STUB = False
  1091. CHIP_DETECT_MAGIC_VALUE = 0x00f01d83
  1092. IROM_MAP_START = 0x400d0000
  1093. IROM_MAP_END = 0x40400000
  1094. DROM_MAP_START = 0x3F400000
  1095. DROM_MAP_END = 0x3F800000
  1096. # ESP32 uses a 4 byte status reply
  1097. STATUS_BYTES_LENGTH = 4
  1098. SPI_REG_BASE = 0x3ff42000
  1099. SPI_USR_OFFS = 0x1c
  1100. SPI_USR1_OFFS = 0x20
  1101. SPI_USR2_OFFS = 0x24
  1102. SPI_MOSI_DLEN_OFFS = 0x28
  1103. SPI_MISO_DLEN_OFFS = 0x2c
  1104. EFUSE_RD_REG_BASE = 0x3ff5a000
  1105. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REG = EFUSE_RD_REG_BASE + 0x18
  1106. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT = (1 << 7) # EFUSE_RD_DISABLE_DL_ENCRYPT
  1107. DR_REG_SYSCON_BASE = 0x3ff66000
  1108. SPI_W0_OFFS = 0x80
  1109. UART_CLKDIV_REG = 0x3ff40014
  1110. XTAL_CLK_DIVIDER = 1
  1111. FLASH_SIZES = {
  1112. '1MB': 0x00,
  1113. '2MB': 0x10,
  1114. '4MB': 0x20,
  1115. '8MB': 0x30,
  1116. '16MB': 0x40
  1117. }
  1118. BOOTLOADER_FLASH_OFFSET = 0x1000
  1119. OVERRIDE_VDDSDIO_CHOICES = ["1.8V", "1.9V", "OFF"]
  1120. MEMORY_MAP = [[0x00000000, 0x00010000, "PADDING"],
  1121. [0x3F400000, 0x3F800000, "DROM"],
  1122. [0x3F800000, 0x3FC00000, "EXTRAM_DATA"],
  1123. [0x3FF80000, 0x3FF82000, "RTC_DRAM"],
  1124. [0x3FF90000, 0x40000000, "BYTE_ACCESSIBLE"],
  1125. [0x3FFAE000, 0x40000000, "DRAM"],
  1126. [0x3FFE0000, 0x3FFFFFFC, "DIRAM_DRAM"],
  1127. [0x40000000, 0x40070000, "IROM"],
  1128. [0x40070000, 0x40078000, "CACHE_PRO"],
  1129. [0x40078000, 0x40080000, "CACHE_APP"],
  1130. [0x40080000, 0x400A0000, "IRAM"],
  1131. [0x400A0000, 0x400BFFFC, "DIRAM_IRAM"],
  1132. [0x400C0000, 0x400C2000, "RTC_IRAM"],
  1133. [0x400D0000, 0x40400000, "IROM"],
  1134. [0x50000000, 0x50002000, "RTC_DATA"]]
  1135. FLASH_ENCRYPTED_WRITE_ALIGN = 32
  1136. """ Try to read the BLOCK1 (encryption key) and check if it is valid """
  1137. def is_flash_encryption_key_valid(self):
  1138. """ Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
  1139. this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """
  1140. word0 = self.read_efuse(0)
  1141. rd_disable = (word0 >> 16) & 0x1
  1142. # reading of BLOCK1 is NOT ALLOWED so we assume valid key is programmed
  1143. if rd_disable:
  1144. return True
  1145. else:
  1146. # reading of BLOCK1 is ALLOWED so we will read and verify for non-zero.
  1147. # When ESP32 has not generated AES/encryption key in BLOCK1, the contents will be readable and 0.
  1148. # If the flash encryption is enabled it is expected to have a valid non-zero key. We break out on
  1149. # first occurance of non-zero value
  1150. key_word = [0] * 7
  1151. for i in range(len(key_word)):
  1152. key_word[i] = self.read_efuse(14 + i)
  1153. # key is non-zero so break & return
  1154. if key_word[i] != 0:
  1155. return True
  1156. return False
  1157. def get_flash_crypt_config(self):
  1158. """ For flash encryption related commands we need to make sure
  1159. user has programmed all the relevant efuse correctly so before
  1160. writing encrypted write_flash_encrypt esptool will verify the values
  1161. of flash_crypt_config to be non zero if they are not read
  1162. protected. If the values are zero a warning will be printed
  1163. bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
  1164. this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """
  1165. word0 = self.read_efuse(0)
  1166. rd_disable = (word0 >> 19) & 0x1
  1167. if rd_disable == 0:
  1168. """ we can read the flash_crypt_config efuse value
  1169. so go & read it (EFUSE_BLK0_RDATA5_REG[31:28]) """
  1170. word5 = self.read_efuse(5)
  1171. word5 = (word5 >> 28) & 0xF
  1172. return word5
  1173. else:
  1174. # if read of the efuse is disabled we assume it is set correctly
  1175. return 0xF
  1176. def get_encrypted_download_disabled(self):
  1177. if self.read_reg(self.EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REG) & self.EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT:
  1178. return True
  1179. else:
  1180. return False
  1181. def get_pkg_version(self):
  1182. word3 = self.read_efuse(3)
  1183. pkg_version = (word3 >> 9) & 0x07
  1184. pkg_version += ((word3 >> 2) & 0x1) << 3
  1185. return pkg_version
  1186. def get_chip_revision(self):
  1187. word3 = self.read_efuse(3)
  1188. word5 = self.read_efuse(5)
  1189. apb_ctl_date = self.read_reg(self.DR_REG_SYSCON_BASE + 0x7C)
  1190. rev_bit0 = (word3 >> 15) & 0x1
  1191. rev_bit1 = (word5 >> 20) & 0x1
  1192. rev_bit2 = (apb_ctl_date >> 31) & 0x1
  1193. if rev_bit0:
  1194. if rev_bit1:
  1195. if rev_bit2:
  1196. return 3
  1197. else:
  1198. return 2
  1199. else:
  1200. return 1
  1201. return 0
  1202. def get_chip_description(self):
  1203. pkg_version = self.get_pkg_version()
  1204. chip_revision = self.get_chip_revision()
  1205. rev3 = (chip_revision == 3)
  1206. single_core = self.read_efuse(3) & (1 << 0) # CHIP_VER DIS_APP_CPU
  1207. chip_name = {
  1208. 0: "ESP32-S0WDQ6" if single_core else "ESP32-D0WDQ6",
  1209. 1: "ESP32-S0WD" if single_core else "ESP32-D0WD",
  1210. 2: "ESP32-D2WD",
  1211. 4: "ESP32-U4WDH",
  1212. 5: "ESP32-PICO-V3" if rev3 else "ESP32-PICO-D4",
  1213. 6: "ESP32-PICO-V3-02",
  1214. }.get(pkg_version, "unknown ESP32")
  1215. # ESP32-D0WD-V3, ESP32-D0WDQ6-V3
  1216. if chip_name.startswith("ESP32-D0WD") and rev3:
  1217. chip_name += "-V3"
  1218. return "%s (revision %d)" % (chip_name, chip_revision)
  1219. def get_chip_features(self):
  1220. features = ["WiFi"]
  1221. word3 = self.read_efuse(3)
  1222. # names of variables in this section are lowercase
  1223. # versions of EFUSE names as documented in TRM and
  1224. # ESP-IDF efuse_reg.h
  1225. chip_ver_dis_bt = word3 & (1 << 1)
  1226. if chip_ver_dis_bt == 0:
  1227. features += ["BT"]
  1228. chip_ver_dis_app_cpu = word3 & (1 << 0)
  1229. if chip_ver_dis_app_cpu:
  1230. features += ["Single Core"]
  1231. else:
  1232. features += ["Dual Core"]
  1233. chip_cpu_freq_rated = word3 & (1 << 13)
  1234. if chip_cpu_freq_rated:
  1235. chip_cpu_freq_low = word3 & (1 << 12)
  1236. if chip_cpu_freq_low:
  1237. features += ["160MHz"]
  1238. else:
  1239. features += ["240MHz"]
  1240. pkg_version = self.get_pkg_version()
  1241. if pkg_version in [2, 4, 5, 6]:
  1242. features += ["Embedded Flash"]
  1243. if pkg_version == 6:
  1244. features += ["Embedded PSRAM"]
  1245. word4 = self.read_efuse(4)
  1246. adc_vref = (word4 >> 8) & 0x1F
  1247. if adc_vref:
  1248. features += ["VRef calibration in efuse"]
  1249. blk3_part_res = word3 >> 14 & 0x1
  1250. if blk3_part_res:
  1251. features += ["BLK3 partially reserved"]
  1252. word6 = self.read_efuse(6)
  1253. coding_scheme = word6 & 0x3
  1254. features += ["Coding Scheme %s" % {
  1255. 0: "None",
  1256. 1: "3/4",
  1257. 2: "Repeat (UNSUPPORTED)",
  1258. 3: "Invalid"}[coding_scheme]]
  1259. return features
  1260. def read_efuse(self, n):
  1261. """ Read the nth word of the ESP3x EFUSE region. """
  1262. return self.read_reg(self.EFUSE_RD_REG_BASE + (4 * n))
  1263. def chip_id(self):
  1264. raise NotSupportedError(self, "chip_id")
  1265. def read_mac(self):
  1266. """ Read MAC from EFUSE region """
  1267. words = [self.read_efuse(2), self.read_efuse(1)]
  1268. bitstring = struct.pack(">II", *words)
  1269. bitstring = bitstring[2:8] # trim the 2 byte CRC
  1270. try:
  1271. return tuple(ord(b) for b in bitstring)
  1272. except TypeError: # Python 3, bitstring elements are already bytes
  1273. return tuple(bitstring)
  1274. def get_erase_size(self, offset, size):
  1275. return size
  1276. def override_vddsdio(self, new_voltage):
  1277. new_voltage = new_voltage.upper()
  1278. if new_voltage not in self.OVERRIDE_VDDSDIO_CHOICES:
  1279. raise FatalError("The only accepted VDDSDIO overrides are '1.8V', '1.9V' and 'OFF'")
  1280. RTC_CNTL_SDIO_CONF_REG = 0x3ff48074
  1281. RTC_CNTL_XPD_SDIO_REG = (1 << 31)
  1282. RTC_CNTL_DREFH_SDIO_M = (3 << 29)
  1283. RTC_CNTL_DREFM_SDIO_M = (3 << 27)
  1284. RTC_CNTL_DREFL_SDIO_M = (3 << 25)
  1285. # RTC_CNTL_SDIO_TIEH = (1 << 23) # not used here, setting TIEH=1 would set 3.3V output, not safe for esptool.py to do
  1286. RTC_CNTL_SDIO_FORCE = (1 << 22)
  1287. RTC_CNTL_SDIO_PD_EN = (1 << 21)
  1288. reg_val = RTC_CNTL_SDIO_FORCE # override efuse setting
  1289. reg_val |= RTC_CNTL_SDIO_PD_EN
  1290. if new_voltage != "OFF":
  1291. reg_val |= RTC_CNTL_XPD_SDIO_REG # enable internal LDO
  1292. if new_voltage == "1.9V":
  1293. reg_val |= (RTC_CNTL_DREFH_SDIO_M | RTC_CNTL_DREFM_SDIO_M | RTC_CNTL_DREFL_SDIO_M) # boost voltage
  1294. self.write_reg(RTC_CNTL_SDIO_CONF_REG, reg_val)
  1295. print("VDDSDIO regulator set to %s" % new_voltage)
  1296. def read_flash_slow(self, offset, length, progress_fn):
  1297. BLOCK_LEN = 64 # ROM read limit per command (this limit is why it's so slow)
  1298. data = b''
  1299. while len(data) < length:
  1300. block_len = min(BLOCK_LEN, length - len(data))
  1301. r = self.check_command("read flash block", self.ESP_READ_FLASH_SLOW,
  1302. struct.pack('<II', offset + len(data), block_len))
  1303. if len(r) < block_len:
  1304. raise FatalError("Expected %d byte block, got %d bytes. Serial errors?" % (block_len, len(r)))
  1305. data += r[:block_len] # command always returns 64 byte buffer, regardless of how many bytes were actually read from flash
  1306. if progress_fn and (len(data) % 1024 == 0 or len(data) == length):
  1307. progress_fn(len(data), length)
  1308. return data
  1309. class ESP32S2ROM(ESP32ROM):
  1310. CHIP_NAME = "ESP32-S2"
  1311. IMAGE_CHIP_ID = 2
  1312. IROM_MAP_START = 0x40080000
  1313. IROM_MAP_END = 0x40b80000
  1314. DROM_MAP_START = 0x3F000000
  1315. DROM_MAP_END = 0x3F3F0000
  1316. CHIP_DETECT_MAGIC_VALUE = 0x000007c6
  1317. SPI_REG_BASE = 0x3f402000
  1318. SPI_USR_OFFS = 0x18
  1319. SPI_USR1_OFFS = 0x1c
  1320. SPI_USR2_OFFS = 0x20
  1321. SPI_MOSI_DLEN_OFFS = 0x24
  1322. SPI_MISO_DLEN_OFFS = 0x28
  1323. SPI_W0_OFFS = 0x58
  1324. MAC_EFUSE_REG = 0x3f41A044 # ESP32-S2 has special block for MAC efuses
  1325. UART_CLKDIV_REG = 0x3f400014
  1326. FLASH_ENCRYPTED_WRITE_ALIGN = 16
  1327. # todo: use espefuse APIs to get this info
  1328. EFUSE_BASE = 0x3f41A000
  1329. EFUSE_RD_REG_BASE = EFUSE_BASE + 0x030 # BLOCK0 read base address
  1330. EFUSE_PURPOSE_KEY0_REG = EFUSE_BASE + 0x34
  1331. EFUSE_PURPOSE_KEY0_SHIFT = 24
  1332. EFUSE_PURPOSE_KEY1_REG = EFUSE_BASE + 0x34
  1333. EFUSE_PURPOSE_KEY1_SHIFT = 28
  1334. EFUSE_PURPOSE_KEY2_REG = EFUSE_BASE + 0x38
  1335. EFUSE_PURPOSE_KEY2_SHIFT = 0
  1336. EFUSE_PURPOSE_KEY3_REG = EFUSE_BASE + 0x38
  1337. EFUSE_PURPOSE_KEY3_SHIFT = 4
  1338. EFUSE_PURPOSE_KEY4_REG = EFUSE_BASE + 0x38
  1339. EFUSE_PURPOSE_KEY4_SHIFT = 8
  1340. EFUSE_PURPOSE_KEY5_REG = EFUSE_BASE + 0x38
  1341. EFUSE_PURPOSE_KEY5_SHIFT = 12
  1342. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REG = EFUSE_RD_REG_BASE
  1343. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT = 1 << 19
  1344. PURPOSE_VAL_XTS_AES256_KEY_1 = 2
  1345. PURPOSE_VAL_XTS_AES256_KEY_2 = 3
  1346. PURPOSE_VAL_XTS_AES128_KEY = 4
  1347. UARTDEV_BUF_NO = 0x3ffffd14 # Variable in ROM .bss which indicates the port in use
  1348. UARTDEV_BUF_NO_USB = 2 # Value of the above variable indicating that USB is in use
  1349. USB_RAM_BLOCK = 0x800 # Max block size USB CDC is used
  1350. GPIO_STRAP_REG = 0x3f404038
  1351. GPIO_STRAP_SPI_BOOT_MASK = 0x8 # Not download mode
  1352. RTC_CNTL_OPTION1_REG = 0x3f408128
  1353. RTC_CNTL_FORCE_DOWNLOAD_BOOT_MASK = 0x1 # Is download mode forced over USB?
  1354. MEMORY_MAP = [[0x00000000, 0x00010000, "PADDING"],
  1355. [0x3F000000, 0x3FF80000, "DROM"],
  1356. [0x3F500000, 0x3FF80000, "EXTRAM_DATA"],
  1357. [0x3FF9E000, 0x3FFA0000, "RTC_DRAM"],
  1358. [0x3FF9E000, 0x40000000, "BYTE_ACCESSIBLE"],
  1359. [0x3FF9E000, 0x40072000, "MEM_INTERNAL"],
  1360. [0x3FFB0000, 0x40000000, "DRAM"],
  1361. [0x40000000, 0x4001A100, "IROM_MASK"],
  1362. [0x40020000, 0x40070000, "IRAM"],
  1363. [0x40070000, 0x40072000, "RTC_IRAM"],
  1364. [0x40080000, 0x40800000, "IROM"],
  1365. [0x50000000, 0x50002000, "RTC_DATA"]]
  1366. def get_pkg_version(self):
  1367. num_word = 3
  1368. block1_addr = self.EFUSE_BASE + 0x044
  1369. word3 = self.read_reg(block1_addr + (4 * num_word))
  1370. pkg_version = (word3 >> 21) & 0x0F
  1371. return pkg_version
  1372. def get_chip_description(self):
  1373. chip_name = {
  1374. 0: "ESP32-S2",
  1375. 1: "ESP32-S2FH16",
  1376. 2: "ESP32-S2FH32",
  1377. }.get(self.get_pkg_version(), "unknown ESP32-S2")
  1378. return "%s" % (chip_name)
  1379. def get_chip_features(self):
  1380. features = ["WiFi"]
  1381. if self.secure_download_mode:
  1382. features += ["Secure Download Mode Enabled"]
  1383. pkg_version = self.get_pkg_version()
  1384. if pkg_version in [1, 2]:
  1385. if pkg_version == 1:
  1386. features += ["Embedded 2MB Flash"]
  1387. elif pkg_version == 2:
  1388. features += ["Embedded 4MB Flash"]
  1389. features += ["105C temp rating"]
  1390. num_word = 4
  1391. block2_addr = self.EFUSE_BASE + 0x05C
  1392. word4 = self.read_reg(block2_addr + (4 * num_word))
  1393. block2_version = (word4 >> 4) & 0x07
  1394. if block2_version == 1:
  1395. features += ["ADC and temperature sensor calibration in BLK2 of efuse"]
  1396. return features
  1397. def get_crystal_freq(self):
  1398. # ESP32-S2 XTAL is fixed to 40MHz
  1399. return 40
  1400. def override_vddsdio(self, new_voltage):
  1401. raise NotImplementedInROMError("VDD_SDIO overrides are not supported for ESP32-S2")
  1402. def read_mac(self):
  1403. mac0 = self.read_reg(self.MAC_EFUSE_REG)
  1404. mac1 = self.read_reg(self.MAC_EFUSE_REG + 4) # only bottom 16 bits are MAC
  1405. bitstring = struct.pack(">II", mac1, mac0)[2:]
  1406. try:
  1407. return tuple(ord(b) for b in bitstring)
  1408. except TypeError: # Python 3, bitstring elements are already bytes
  1409. return tuple(bitstring)
  1410. def get_flash_crypt_config(self):
  1411. return None # doesn't exist on ESP32-S2
  1412. def get_key_block_purpose(self, key_block):
  1413. if key_block < 0 or key_block > 5:
  1414. raise FatalError("Valid key block numbers must be in range 0-5")
  1415. reg, shift = [(self.EFUSE_PURPOSE_KEY0_REG, self.EFUSE_PURPOSE_KEY0_SHIFT),
  1416. (self.EFUSE_PURPOSE_KEY1_REG, self.EFUSE_PURPOSE_KEY1_SHIFT),
  1417. (self.EFUSE_PURPOSE_KEY2_REG, self.EFUSE_PURPOSE_KEY2_SHIFT),
  1418. (self.EFUSE_PURPOSE_KEY3_REG, self.EFUSE_PURPOSE_KEY3_SHIFT),
  1419. (self.EFUSE_PURPOSE_KEY4_REG, self.EFUSE_PURPOSE_KEY4_SHIFT),
  1420. (self.EFUSE_PURPOSE_KEY5_REG, self.EFUSE_PURPOSE_KEY5_SHIFT)][key_block]
  1421. return (self.read_reg(reg) >> shift) & 0xF
  1422. def is_flash_encryption_key_valid(self):
  1423. # Need to see either an AES-128 key or two AES-256 keys
  1424. purposes = [self.get_key_block_purpose(b) for b in range(6)]
  1425. if any(p == self.PURPOSE_VAL_XTS_AES128_KEY for p in purposes):
  1426. return True
  1427. return any(p == self.PURPOSE_VAL_XTS_AES256_KEY_1 for p in purposes) \
  1428. and any(p == self.PURPOSE_VAL_XTS_AES256_KEY_2 for p in purposes)
  1429. def uses_usb(self, _cache=[]):
  1430. if self.secure_download_mode:
  1431. return False # can't detect native USB in secure download mode
  1432. if not _cache:
  1433. buf_no = self.read_reg(self.UARTDEV_BUF_NO) & 0xff
  1434. _cache.append(buf_no == self.UARTDEV_BUF_NO_USB)
  1435. return _cache[0]
  1436. def _post_connect(self):
  1437. if self.uses_usb():
  1438. self.ESP_RAM_BLOCK = self.USB_RAM_BLOCK
  1439. def _check_if_can_reset(self):
  1440. """
  1441. Check the strapping register to see if we can reset out of download mode.
  1442. """
  1443. if os.getenv("ESPTOOL_TESTING") is not None:
  1444. print("ESPTOOL_TESTING is set, ignoring strapping mode check")
  1445. # Esptool tests over USB CDC run with GPIO0 strapped low, don't complain in this case.
  1446. return
  1447. strap_reg = self.read_reg(self.GPIO_STRAP_REG)
  1448. force_dl_reg = self.read_reg(self.RTC_CNTL_OPTION1_REG)
  1449. if strap_reg & self.GPIO_STRAP_SPI_BOOT_MASK == 0 and force_dl_reg & self.RTC_CNTL_FORCE_DOWNLOAD_BOOT_MASK == 0:
  1450. print("ERROR: {} chip was placed into download mode using GPIO0.\n"
  1451. "esptool.py can not exit the download mode over USB. "
  1452. "To run the app, reset the chip manually.\n"
  1453. "To suppress this error, set --after option to 'no_reset'.".format(self.get_chip_description()))
  1454. raise SystemExit(1)
  1455. def hard_reset(self):
  1456. if self.uses_usb():
  1457. self._check_if_can_reset()
  1458. self._setRTS(True) # EN->LOW
  1459. if self.uses_usb():
  1460. # Give the chip some time to come out of reset, to be able to handle further DTR/RTS transitions
  1461. time.sleep(0.2)
  1462. self._setRTS(False)
  1463. time.sleep(0.2)
  1464. else:
  1465. self._setRTS(False)
  1466. class ESP32S3BETA2ROM(ESP32ROM):
  1467. CHIP_NAME = "ESP32-S3(beta2)"
  1468. IMAGE_CHIP_ID = 4
  1469. IROM_MAP_START = 0x42000000
  1470. IROM_MAP_END = 0x44000000
  1471. DROM_MAP_START = 0x3c000000
  1472. DROM_MAP_END = 0x3e000000
  1473. UART_DATE_REG_ADDR = 0x60000080
  1474. CHIP_DETECT_MAGIC_VALUE = 0xeb004136
  1475. SPI_REG_BASE = 0x60002000
  1476. SPI_USR_OFFS = 0x18
  1477. SPI_USR1_OFFS = 0x1c
  1478. SPI_USR2_OFFS = 0x20
  1479. SPI_MOSI_DLEN_OFFS = 0x24
  1480. SPI_MISO_DLEN_OFFS = 0x28
  1481. SPI_W0_OFFS = 0x58
  1482. EFUSE_REG_BASE = 0x6001A030 # BLOCK0 read base address
  1483. MAC_EFUSE_REG = 0x6001A000 # ESP32S3 has special block for MAC efuses
  1484. UART_CLKDIV_REG = 0x60000014
  1485. GPIO_STRAP_REG = 0x60004038
  1486. MEMORY_MAP = [[0x00000000, 0x00010000, "PADDING"],
  1487. [0x3C000000, 0x3D000000, "DROM"],
  1488. [0x3D000000, 0x3E000000, "EXTRAM_DATA"],
  1489. [0x600FE000, 0x60100000, "RTC_DRAM"],
  1490. [0x3FC88000, 0x3FD00000, "BYTE_ACCESSIBLE"],
  1491. [0x3FC88000, 0x403E2000, "MEM_INTERNAL"],
  1492. [0x3FC88000, 0x3FD00000, "DRAM"],
  1493. [0x40000000, 0x4001A100, "IROM_MASK"],
  1494. [0x40370000, 0x403E0000, "IRAM"],
  1495. [0x600FE000, 0x60100000, "RTC_IRAM"],
  1496. [0x42000000, 0x42800000, "IROM"],
  1497. [0x50000000, 0x50002000, "RTC_DATA"]]
  1498. def get_chip_description(self):
  1499. return "ESP32-S3(beta2)"
  1500. def get_chip_features(self):
  1501. return ["WiFi", "BLE"]
  1502. def get_crystal_freq(self):
  1503. # ESP32S3 XTAL is fixed to 40MHz
  1504. return 40
  1505. def override_vddsdio(self, new_voltage):
  1506. raise NotImplementedInROMError("VDD_SDIO overrides are not supported for ESP32-S3")
  1507. def read_mac(self):
  1508. mac0 = self.read_reg(self.MAC_EFUSE_REG)
  1509. mac1 = self.read_reg(self.MAC_EFUSE_REG + 4) # only bottom 16 bits are MAC
  1510. bitstring = struct.pack(">II", mac1, mac0)[2:]
  1511. try:
  1512. return tuple(ord(b) for b in bitstring)
  1513. except TypeError: # Python 3, bitstring elements are already bytes
  1514. return tuple(bitstring)
  1515. class ESP32S3BETA3ROM(ESP32ROM):
  1516. CHIP_NAME = "ESP32-S3(beta3)"
  1517. IMAGE_CHIP_ID = 6
  1518. IROM_MAP_START = 0x42000000
  1519. IROM_MAP_END = 0x44000000
  1520. DROM_MAP_START = 0x3c000000
  1521. DROM_MAP_END = 0x3e000000
  1522. UART_DATE_REG_ADDR = 0x60000080
  1523. CHIP_DETECT_MAGIC_VALUE = 0x9
  1524. SPI_REG_BASE = 0x60002000
  1525. SPI_USR_OFFS = 0x18
  1526. SPI_USR1_OFFS = 0x1c
  1527. SPI_USR2_OFFS = 0x20
  1528. SPI_MOSI_DLEN_OFFS = 0x24
  1529. SPI_MISO_DLEN_OFFS = 0x28
  1530. SPI_W0_OFFS = 0x58
  1531. EFUSE_BASE = 0x6001A000 # BLOCK0 read base address
  1532. MAC_EFUSE_REG = EFUSE_BASE + 0x044 # ESP32S3 has special block for MAC efuses
  1533. UART_CLKDIV_REG = 0x60000014
  1534. GPIO_STRAP_REG = 0x60004038
  1535. MEMORY_MAP = [[0x00000000, 0x00010000, "PADDING"],
  1536. [0x3C000000, 0x3D000000, "DROM"],
  1537. [0x3D000000, 0x3E000000, "EXTRAM_DATA"],
  1538. [0x600FE000, 0x60100000, "RTC_DRAM"],
  1539. [0x3FC88000, 0x3FD00000, "BYTE_ACCESSIBLE"],
  1540. [0x3FC88000, 0x403E2000, "MEM_INTERNAL"],
  1541. [0x3FC88000, 0x3FD00000, "DRAM"],
  1542. [0x40000000, 0x4001A100, "IROM_MASK"],
  1543. [0x40370000, 0x403E0000, "IRAM"],
  1544. [0x600FE000, 0x60100000, "RTC_IRAM"],
  1545. [0x42000000, 0x42800000, "IROM"],
  1546. [0x50000000, 0x50002000, "RTC_DATA"]]
  1547. def get_chip_description(self):
  1548. return "ESP32-S3(beta3)"
  1549. def get_chip_features(self):
  1550. return ["WiFi", "BLE"]
  1551. def get_crystal_freq(self):
  1552. # ESP32S3 XTAL is fixed to 40MHz
  1553. return 40
  1554. def override_vddsdio(self, new_voltage):
  1555. raise NotImplementedInROMError("VDD_SDIO overrides are not supported for ESP32-S3")
  1556. def read_mac(self):
  1557. mac0 = self.read_reg(self.MAC_EFUSE_REG)
  1558. mac1 = self.read_reg(self.MAC_EFUSE_REG + 4) # only bottom 16 bits are MAC
  1559. bitstring = struct.pack(">II", mac1, mac0)[2:]
  1560. try:
  1561. return tuple(ord(b) for b in bitstring)
  1562. except TypeError: # Python 3, bitstring elements are already bytes
  1563. return tuple(bitstring)
  1564. class ESP32C3ROM(ESP32ROM):
  1565. CHIP_NAME = "ESP32-C3"
  1566. IMAGE_CHIP_ID = 5
  1567. IROM_MAP_START = 0x42000000
  1568. IROM_MAP_END = 0x42800000
  1569. DROM_MAP_START = 0x3c000000
  1570. DROM_MAP_END = 0x3c800000
  1571. SPI_REG_BASE = 0x60002000
  1572. SPI_USR_OFFS = 0x18
  1573. SPI_USR1_OFFS = 0x1C
  1574. SPI_USR2_OFFS = 0x20
  1575. SPI_MOSI_DLEN_OFFS = 0x24
  1576. SPI_MISO_DLEN_OFFS = 0x28
  1577. SPI_W0_OFFS = 0x58
  1578. BOOTLOADER_FLASH_OFFSET = 0x0
  1579. CHIP_DETECT_MAGIC_VALUE = 0x6921506f
  1580. UART_DATE_REG_ADDR = 0x60000000 + 0x7c
  1581. EFUSE_BASE = 0x60008800
  1582. MAC_EFUSE_REG = EFUSE_BASE + 0x044
  1583. EFUSE_RD_REG_BASE = EFUSE_BASE + 0x030 # BLOCK0 read base address
  1584. EFUSE_PURPOSE_KEY0_REG = EFUSE_BASE + 0x34
  1585. EFUSE_PURPOSE_KEY0_SHIFT = 24
  1586. EFUSE_PURPOSE_KEY1_REG = EFUSE_BASE + 0x34
  1587. EFUSE_PURPOSE_KEY1_SHIFT = 28
  1588. EFUSE_PURPOSE_KEY2_REG = EFUSE_BASE + 0x38
  1589. EFUSE_PURPOSE_KEY2_SHIFT = 0
  1590. EFUSE_PURPOSE_KEY3_REG = EFUSE_BASE + 0x38
  1591. EFUSE_PURPOSE_KEY3_SHIFT = 4
  1592. EFUSE_PURPOSE_KEY4_REG = EFUSE_BASE + 0x38
  1593. EFUSE_PURPOSE_KEY4_SHIFT = 8
  1594. EFUSE_PURPOSE_KEY5_REG = EFUSE_BASE + 0x38
  1595. EFUSE_PURPOSE_KEY5_SHIFT = 12
  1596. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REG = EFUSE_RD_REG_BASE
  1597. EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT = 1 << 20
  1598. PURPOSE_VAL_XTS_AES128_KEY = 4
  1599. GPIO_STRAP_REG = 0x3f404038
  1600. FLASH_ENCRYPTED_WRITE_ALIGN = 16
  1601. MEMORY_MAP = [[0x00000000, 0x00010000, "PADDING"],
  1602. [0x3C000000, 0x3C800000, "DROM"],
  1603. [0x3FC80000, 0x3FCE0000, "DRAM"],
  1604. [0x3FC88000, 0x3FD00000, "BYTE_ACCESSIBLE"],
  1605. [0x3FF00000, 0x3FF20000, "DROM_MASK"],
  1606. [0x40000000, 0x40060000, "IROM_MASK"],
  1607. [0x42000000, 0x42800000, "IROM"],
  1608. [0x4037C000, 0x403E0000, "IRAM"],
  1609. [0x50000000, 0x50002000, "RTC_IRAM"],
  1610. [0x50000000, 0x50002000, "RTC_DRAM"],
  1611. [0x600FE000, 0x60100000, "MEM_INTERNAL2"]]
  1612. def get_pkg_version(self):
  1613. num_word = 3
  1614. block1_addr = self.EFUSE_BASE + 0x044
  1615. word3 = self.read_reg(block1_addr + (4 * num_word))
  1616. pkg_version = (word3 >> 21) & 0x0F
  1617. return pkg_version
  1618. def get_chip_revision(self):
  1619. # reads WAFER_VERSION field from EFUSE_RD_MAC_SPI_SYS_3_REG
  1620. block1_addr = self.EFUSE_BASE + 0x044
  1621. num_word = 3
  1622. pos = 18
  1623. return (self.read_reg(block1_addr + (4 * num_word)) & (0x7 << pos)) >> pos
  1624. def get_chip_description(self):
  1625. chip_name = {
  1626. 0: "ESP32-C3",
  1627. }.get(self.get_pkg_version(), "unknown ESP32-C3")
  1628. chip_revision = self.get_chip_revision()
  1629. return "%s (revision %d)" % (chip_name, chip_revision)
  1630. def get_chip_features(self):
  1631. return ["Wi-Fi"]
  1632. def get_crystal_freq(self):
  1633. # ESP32C3 XTAL is fixed to 40MHz
  1634. return 40
  1635. def override_vddsdio(self, new_voltage):
  1636. raise NotImplementedInROMError("VDD_SDIO overrides are not supported for ESP32-C3")
  1637. def read_mac(self):
  1638. mac0 = self.read_reg(self.MAC_EFUSE_REG)
  1639. mac1 = self.read_reg(self.MAC_EFUSE_REG + 4) # only bottom 16 bits are MAC
  1640. bitstring = struct.pack(">II", mac1, mac0)[2:]
  1641. try:
  1642. return tuple(ord(b) for b in bitstring)
  1643. except TypeError: # Python 3, bitstring elements are already bytes
  1644. return tuple(bitstring)
  1645. def get_flash_crypt_config(self):
  1646. return None # doesn't exist on ESP32-C3
  1647. def get_key_block_purpose(self, key_block):
  1648. if key_block < 0 or key_block > 5:
  1649. raise FatalError("Valid key block numbers must be in range 0-5")
  1650. reg, shift = [(self.EFUSE_PURPOSE_KEY0_REG, self.EFUSE_PURPOSE_KEY0_SHIFT),
  1651. (self.EFUSE_PURPOSE_KEY1_REG, self.EFUSE_PURPOSE_KEY1_SHIFT),
  1652. (self.EFUSE_PURPOSE_KEY2_REG, self.EFUSE_PURPOSE_KEY2_SHIFT),
  1653. (self.EFUSE_PURPOSE_KEY3_REG, self.EFUSE_PURPOSE_KEY3_SHIFT),
  1654. (self.EFUSE_PURPOSE_KEY4_REG, self.EFUSE_PURPOSE_KEY4_SHIFT),
  1655. (self.EFUSE_PURPOSE_KEY5_REG, self.EFUSE_PURPOSE_KEY5_SHIFT)][key_block]
  1656. return (self.read_reg(reg) >> shift) & 0xF
  1657. def is_flash_encryption_key_valid(self):
  1658. # Need to see an AES-128 key
  1659. purposes = [self.get_key_block_purpose(b) for b in range(6)]
  1660. return any(p == self.PURPOSE_VAL_XTS_AES128_KEY for p in purposes)
  1661. class ESP32StubLoader(ESP32ROM):
  1662. """ Access class for ESP32 stub loader, runs on top of ROM.
  1663. """
  1664. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1665. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1666. IS_STUB = True
  1667. def __init__(self, rom_loader):
  1668. self.secure_download_mode = rom_loader.secure_download_mode
  1669. self._port = rom_loader._port
  1670. self._trace_enabled = rom_loader._trace_enabled
  1671. self.flush_input() # resets _slip_reader
  1672. ESP32ROM.STUB_CLASS = ESP32StubLoader
  1673. class ESP32S2StubLoader(ESP32S2ROM):
  1674. """ Access class for ESP32-S2 stub loader, runs on top of ROM.
  1675. (Basically the same as ESP32StubLoader, but different base class.
  1676. Can possibly be made into a mixin.)
  1677. """
  1678. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1679. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1680. IS_STUB = True
  1681. def __init__(self, rom_loader):
  1682. self.secure_download_mode = rom_loader.secure_download_mode
  1683. self._port = rom_loader._port
  1684. self._trace_enabled = rom_loader._trace_enabled
  1685. self.flush_input() # resets _slip_reader
  1686. if rom_loader.uses_usb():
  1687. self.ESP_RAM_BLOCK = self.USB_RAM_BLOCK
  1688. self.FLASH_WRITE_SIZE = self.USB_RAM_BLOCK
  1689. ESP32S2ROM.STUB_CLASS = ESP32S2StubLoader
  1690. class ESP32S3BETA2StubLoader(ESP32S3BETA2ROM):
  1691. """ Access class for ESP32S3 stub loader, runs on top of ROM.
  1692. (Basically the same as ESP32StubLoader, but different base class.
  1693. Can possibly be made into a mixin.)
  1694. """
  1695. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1696. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1697. IS_STUB = True
  1698. def __init__(self, rom_loader):
  1699. self.secure_download_mode = rom_loader.secure_download_mode
  1700. self._port = rom_loader._port
  1701. self._trace_enabled = rom_loader._trace_enabled
  1702. self.flush_input() # resets _slip_reader
  1703. ESP32S3BETA2ROM.STUB_CLASS = ESP32S3BETA2StubLoader
  1704. class ESP32S3BETA3StubLoader(ESP32S3BETA3ROM):
  1705. """ Access class for ESP32S3 stub loader, runs on top of ROM.
  1706. (Basically the same as ESP32StubLoader, but different base class.
  1707. Can possibly be made into a mixin.)
  1708. """
  1709. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1710. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1711. IS_STUB = True
  1712. def __init__(self, rom_loader):
  1713. self.secure_download_mode = rom_loader.secure_download_mode
  1714. self._port = rom_loader._port
  1715. self._trace_enabled = rom_loader._trace_enabled
  1716. self.flush_input() # resets _slip_reader
  1717. ESP32S3BETA3ROM.STUB_CLASS = ESP32S3BETA3StubLoader
  1718. class ESP32C3StubLoader(ESP32C3ROM):
  1719. """ Access class for ESP32C3 stub loader, runs on top of ROM.
  1720. (Basically the same as ESP32StubLoader, but different base class.
  1721. Can possibly be made into a mixin.)
  1722. """
  1723. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1724. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1725. IS_STUB = True
  1726. def __init__(self, rom_loader):
  1727. self.secure_download_mode = rom_loader.secure_download_mode
  1728. self._port = rom_loader._port
  1729. self._trace_enabled = rom_loader._trace_enabled
  1730. self.flush_input() # resets _slip_reader
  1731. ESP32C3ROM.STUB_CLASS = ESP32C3StubLoader
  1732. class ESPBOOTLOADER(object):
  1733. """ These are constants related to software ESP8266 bootloader, working with 'v2' image files """
  1734. # First byte of the "v2" application image
  1735. IMAGE_V2_MAGIC = 0xea
  1736. # First 'segment' value in a "v2" application image, appears to be a constant version value?
  1737. IMAGE_V2_SEGMENT = 4
  1738. def LoadFirmwareImage(chip, filename):
  1739. """ Load a firmware image. Can be for any supported SoC.
  1740. ESP8266 images will be examined to determine if they are original ROM firmware images (ESP8266ROMFirmwareImage)
  1741. or "v2" OTA bootloader images.
  1742. Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2).
  1743. """
  1744. chip = chip.lower().replace("-", "")
  1745. with open(filename, 'rb') as f:
  1746. if chip == 'esp32':
  1747. return ESP32FirmwareImage(f)
  1748. elif chip == "esp32s2":
  1749. return ESP32S2FirmwareImage(f)
  1750. elif chip == "esp32s3beta2":
  1751. return ESP32S3BETA2FirmwareImage(f)
  1752. elif chip == "esp32s3beta3":
  1753. return ESP32S3BETA3FirmwareImage(f)
  1754. elif chip == 'esp32c3':
  1755. return ESP32C3FirmwareImage(f)
  1756. else: # Otherwise, ESP8266 so look at magic to determine the image type
  1757. magic = ord(f.read(1))
  1758. f.seek(0)
  1759. if magic == ESPLoader.ESP_IMAGE_MAGIC:
  1760. return ESP8266ROMFirmwareImage(f)
  1761. elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
  1762. return ESP8266V2FirmwareImage(f)
  1763. else:
  1764. raise FatalError("Invalid image magic number: %d" % magic)
  1765. class ImageSegment(object):
  1766. """ Wrapper class for a segment in an ESP image
  1767. (very similar to a section in an ELFImage also) """
  1768. def __init__(self, addr, data, file_offs=None):
  1769. self.addr = addr
  1770. self.data = data
  1771. self.file_offs = file_offs
  1772. self.include_in_checksum = True
  1773. if self.addr != 0:
  1774. self.pad_to_alignment(4) # pad all "real" ImageSegments 4 byte aligned length
  1775. def copy_with_new_addr(self, new_addr):
  1776. """ Return a new ImageSegment with same data, but mapped at
  1777. a new address. """
  1778. return ImageSegment(new_addr, self.data, 0)
  1779. def split_image(self, split_len):
  1780. """ Return a new ImageSegment which splits "split_len" bytes
  1781. from the beginning of the data. Remaining bytes are kept in
  1782. this segment object (and the start address is adjusted to match.) """
  1783. result = copy.copy(self)
  1784. result.data = self.data[:split_len]
  1785. self.data = self.data[split_len:]
  1786. self.addr += split_len
  1787. self.file_offs = None
  1788. result.file_offs = None
  1789. return result
  1790. def __repr__(self):
  1791. r = "len 0x%05x load 0x%08x" % (len(self.data), self.addr)
  1792. if self.file_offs is not None:
  1793. r += " file_offs 0x%08x" % (self.file_offs)
  1794. return r
  1795. def get_memory_type(self, image):
  1796. """
  1797. Return a list describing the memory type(s) that is covered by this
  1798. segment's start address.
  1799. """
  1800. return [map_range[2] for map_range in image.ROM_LOADER.MEMORY_MAP if map_range[0] <= self.addr < map_range[1]]
  1801. def pad_to_alignment(self, alignment):
  1802. self.data = pad_to(self.data, alignment, b'\x00')
  1803. class ELFSection(ImageSegment):
  1804. """ Wrapper class for a section in an ELF image, has a section
  1805. name as well as the common properties of an ImageSegment. """
  1806. def __init__(self, name, addr, data):
  1807. super(ELFSection, self).__init__(addr, data)
  1808. self.name = name.decode("utf-8")
  1809. def __repr__(self):
  1810. return "%s %s" % (self.name, super(ELFSection, self).__repr__())
  1811. class BaseFirmwareImage(object):
  1812. SEG_HEADER_LEN = 8
  1813. SHA256_DIGEST_LEN = 32
  1814. """ Base class with common firmware image functions """
  1815. def __init__(self):
  1816. self.segments = []
  1817. self.entrypoint = 0
  1818. self.elf_sha256 = None
  1819. self.elf_sha256_offset = 0
  1820. def load_common_header(self, load_file, expected_magic):
  1821. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  1822. if magic != expected_magic:
  1823. raise FatalError('Invalid firmware image magic=0x%x' % (magic))
  1824. return segments
  1825. def verify(self):
  1826. if len(self.segments) > 16:
  1827. raise FatalError('Invalid segment count %d (max 16). Usually this indicates a linker script problem.' % len(self.segments))
  1828. def load_segment(self, f, is_irom_segment=False):
  1829. """ Load the next segment from the image file """
  1830. file_offs = f.tell()
  1831. (offset, size) = struct.unpack('<II', f.read(8))
  1832. self.warn_if_unusual_segment(offset, size, is_irom_segment)
  1833. segment_data = f.read(size)
  1834. if len(segment_data) < size:
  1835. raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
  1836. segment = ImageSegment(offset, segment_data, file_offs)
  1837. self.segments.append(segment)
  1838. return segment
  1839. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  1840. if not is_irom_segment:
  1841. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  1842. print('WARNING: Suspicious segment 0x%x, length %d' % (offset, size))
  1843. def maybe_patch_segment_data(self, f, segment_data):
  1844. """If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data."""
  1845. segment_len = len(segment_data)
  1846. file_pos = f.tell() # file_pos is position in the .bin file
  1847. if self.elf_sha256_offset >= file_pos and self.elf_sha256_offset < file_pos + segment_len:
  1848. # SHA256 digest needs to be patched into this binary segment,
  1849. # calculate offset of the digest inside the binary segment.
  1850. patch_offset = self.elf_sha256_offset - file_pos
  1851. # Sanity checks
  1852. if patch_offset < self.SEG_HEADER_LEN or patch_offset + self.SHA256_DIGEST_LEN > segment_len:
  1853. raise FatalError('Cannot place SHA256 digest on segment boundary'
  1854. '(elf_sha256_offset=%d, file_pos=%d, segment_size=%d)' %
  1855. (self.elf_sha256_offset, file_pos, segment_len))
  1856. # offset relative to the data part
  1857. patch_offset -= self.SEG_HEADER_LEN
  1858. if segment_data[patch_offset:patch_offset + self.SHA256_DIGEST_LEN] != b'\x00' * self.SHA256_DIGEST_LEN:
  1859. raise FatalError('Contents of segment at SHA256 digest offset 0x%x are not all zero. Refusing to overwrite.' %
  1860. self.elf_sha256_offset)
  1861. assert(len(self.elf_sha256) == self.SHA256_DIGEST_LEN)
  1862. segment_data = segment_data[0:patch_offset] + self.elf_sha256 + \
  1863. segment_data[patch_offset + self.SHA256_DIGEST_LEN:]
  1864. return segment_data
  1865. def save_segment(self, f, segment, checksum=None):
  1866. """ Save the next segment to the image file, return next checksum value if provided """
  1867. segment_data = self.maybe_patch_segment_data(f, segment.data)
  1868. f.write(struct.pack('<II', segment.addr, len(segment_data)))
  1869. f.write(segment_data)
  1870. if checksum is not None:
  1871. return ESPLoader.checksum(segment_data, checksum)
  1872. def read_checksum(self, f):
  1873. """ Return ESPLoader checksum from end of just-read image """
  1874. # Skip the padding. The checksum is stored in the last byte so that the
  1875. # file is a multiple of 16 bytes.
  1876. align_file_position(f, 16)
  1877. return ord(f.read(1))
  1878. def calculate_checksum(self):
  1879. """ Calculate checksum of loaded image, based on segments in
  1880. segment array.
  1881. """
  1882. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1883. for seg in self.segments:
  1884. if seg.include_in_checksum:
  1885. checksum = ESPLoader.checksum(seg.data, checksum)
  1886. return checksum
  1887. def append_checksum(self, f, checksum):
  1888. """ Append ESPLoader checksum to the just-written image """
  1889. align_file_position(f, 16)
  1890. f.write(struct.pack(b'B', checksum))
  1891. def write_common_header(self, f, segments):
  1892. f.write(struct.pack('<BBBBI', ESPLoader.ESP_IMAGE_MAGIC, len(segments),
  1893. self.flash_mode, self.flash_size_freq, self.entrypoint))
  1894. def is_irom_addr(self, addr):
  1895. """ Returns True if an address starts in the irom region.
  1896. Valid for ESP8266 only.
  1897. """
  1898. return ESP8266ROM.IROM_MAP_START <= addr < ESP8266ROM.IROM_MAP_END
  1899. def get_irom_segment(self):
  1900. irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)]
  1901. if len(irom_segments) > 0:
  1902. if len(irom_segments) != 1:
  1903. raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
  1904. return irom_segments[0]
  1905. return None
  1906. def get_non_irom_segments(self):
  1907. irom_segment = self.get_irom_segment()
  1908. return [s for s in self.segments if s != irom_segment]
  1909. def merge_adjacent_segments(self):
  1910. if not self.segments:
  1911. return # nothing to merge
  1912. segments = []
  1913. # The easiest way to merge the sections is the browse them backward.
  1914. for i in range(len(self.segments) - 1, 0, -1):
  1915. # elem is the previous section, the one `next_elem` may need to be
  1916. # merged in
  1917. elem = self.segments[i - 1]
  1918. next_elem = self.segments[i]
  1919. if all((elem.get_memory_type(self) == next_elem.get_memory_type(self),
  1920. elem.include_in_checksum == next_elem.include_in_checksum,
  1921. next_elem.addr == elem.addr + len(elem.data))):
  1922. # Merge any segment that ends where the next one starts, without spanning memory types
  1923. #
  1924. # (don't 'pad' any gaps here as they may be excluded from the image due to 'noinit'
  1925. # or other reasons.)
  1926. elem.data += next_elem.data
  1927. else:
  1928. # The section next_elem cannot be merged into the previous one,
  1929. # which means it needs to be part of the final segments.
  1930. # As we are browsing the list backward, the elements need to be
  1931. # inserted at the beginning of the final list.
  1932. segments.insert(0, next_elem)
  1933. # The first segment will always be here as it cannot be merged into any
  1934. # "previous" section.
  1935. segments.insert(0, self.segments[0])
  1936. # note: we could sort segments here as well, but the ordering of segments is sometimes
  1937. # important for other reasons (like embedded ELF SHA-256), so we assume that the linker
  1938. # script will have produced any adjacent sections in linear order in the ELF, anyhow.
  1939. self.segments = segments
  1940. class ESP8266ROMFirmwareImage(BaseFirmwareImage):
  1941. """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
  1942. ROM_LOADER = ESP8266ROM
  1943. def __init__(self, load_file=None):
  1944. super(ESP8266ROMFirmwareImage, self).__init__()
  1945. self.flash_mode = 0
  1946. self.flash_size_freq = 0
  1947. self.version = 1
  1948. if load_file is not None:
  1949. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  1950. for _ in range(segments):
  1951. self.load_segment(load_file)
  1952. self.checksum = self.read_checksum(load_file)
  1953. self.verify()
  1954. def default_output_name(self, input_file):
  1955. """ Derive a default output name from the ELF name. """
  1956. return input_file + '-'
  1957. def save(self, basename):
  1958. """ Save a set of V1 images for flashing. Parameter is a base filename. """
  1959. # IROM data goes in its own plain binary file
  1960. irom_segment = self.get_irom_segment()
  1961. if irom_segment is not None:
  1962. with open("%s0x%05x.bin" % (basename, irom_segment.addr - ESP8266ROM.IROM_MAP_START), "wb") as f:
  1963. f.write(irom_segment.data)
  1964. # everything but IROM goes at 0x00000 in an image file
  1965. normal_segments = self.get_non_irom_segments()
  1966. with open("%s0x00000.bin" % basename, 'wb') as f:
  1967. self.write_common_header(f, normal_segments)
  1968. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1969. for segment in normal_segments:
  1970. checksum = self.save_segment(f, segment, checksum)
  1971. self.append_checksum(f, checksum)
  1972. ESP8266ROM.BOOTLOADER_IMAGE = ESP8266ROMFirmwareImage
  1973. class ESP8266V2FirmwareImage(BaseFirmwareImage):
  1974. """ 'Version 2' firmware image, segments loaded by software bootloader stub
  1975. (ie Espressif bootloader or rboot)
  1976. """
  1977. ROM_LOADER = ESP8266ROM
  1978. def __init__(self, load_file=None):
  1979. super(ESP8266V2FirmwareImage, self).__init__()
  1980. self.version = 2
  1981. if load_file is not None:
  1982. segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC)
  1983. if segments != ESPBOOTLOADER.IMAGE_V2_SEGMENT:
  1984. # segment count is not really segment count here, but we expect to see '4'
  1985. print('Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments)
  1986. # irom segment comes before the second header
  1987. #
  1988. # the file is saved in the image with a zero load address
  1989. # in the header, so we need to calculate a load address
  1990. irom_segment = self.load_segment(load_file, True)
  1991. irom_segment.addr = 0 # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_addr + 8
  1992. irom_segment.include_in_checksum = False
  1993. first_flash_mode = self.flash_mode
  1994. first_flash_size_freq = self.flash_size_freq
  1995. first_entrypoint = self.entrypoint
  1996. # load the second header
  1997. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  1998. if first_flash_mode != self.flash_mode:
  1999. print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  2000. % (first_flash_mode, self.flash_mode))
  2001. if first_flash_size_freq != self.flash_size_freq:
  2002. print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  2003. % (first_flash_size_freq, self.flash_size_freq))
  2004. if first_entrypoint != self.entrypoint:
  2005. print('WARNING: Entrypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
  2006. % (first_entrypoint, self.entrypoint))
  2007. # load all the usual segments
  2008. for _ in range(segments):
  2009. self.load_segment(load_file)
  2010. self.checksum = self.read_checksum(load_file)
  2011. self.verify()
  2012. def default_output_name(self, input_file):
  2013. """ Derive a default output name from the ELF name. """
  2014. irom_segment = self.get_irom_segment()
  2015. if irom_segment is not None:
  2016. irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
  2017. else:
  2018. irom_offs = 0
  2019. return "%s-0x%05x.bin" % (os.path.splitext(input_file)[0],
  2020. irom_offs & ~(ESPLoader.FLASH_SECTOR_SIZE - 1))
  2021. def save(self, filename):
  2022. with open(filename, 'wb') as f:
  2023. # Save first header for irom0 segment
  2024. f.write(struct.pack(b'<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
  2025. self.flash_mode, self.flash_size_freq, self.entrypoint))
  2026. irom_segment = self.get_irom_segment()
  2027. if irom_segment is not None:
  2028. # save irom0 segment, make sure it has load addr 0 in the file
  2029. irom_segment = irom_segment.copy_with_new_addr(0)
  2030. irom_segment.pad_to_alignment(16) # irom_segment must end on a 16 byte boundary
  2031. self.save_segment(f, irom_segment)
  2032. # second header, matches V1 header and contains loadable segments
  2033. normal_segments = self.get_non_irom_segments()
  2034. self.write_common_header(f, normal_segments)
  2035. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  2036. for segment in normal_segments:
  2037. checksum = self.save_segment(f, segment, checksum)
  2038. self.append_checksum(f, checksum)
  2039. # calculate a crc32 of entire file and append
  2040. # (algorithm used by recent 8266 SDK bootloaders)
  2041. with open(filename, 'rb') as f:
  2042. crc = esp8266_crc32(f.read())
  2043. with open(filename, 'ab') as f:
  2044. f.write(struct.pack(b'<I', crc))
  2045. # Backwards compatibility for previous API, remove in esptool.py V3
  2046. ESPFirmwareImage = ESP8266ROMFirmwareImage
  2047. OTAFirmwareImage = ESP8266V2FirmwareImage
  2048. def esp8266_crc32(data):
  2049. """
  2050. CRC32 algorithm used by 8266 SDK bootloader (and gen_appbin.py).
  2051. """
  2052. crc = binascii.crc32(data, 0) & 0xFFFFFFFF
  2053. if crc & 0x80000000:
  2054. return crc ^ 0xFFFFFFFF
  2055. else:
  2056. return crc + 1
  2057. class ESP32FirmwareImage(BaseFirmwareImage):
  2058. """ ESP32 firmware image is very similar to V1 ESP8266 image,
  2059. except with an additional 16 byte reserved header at top of image,
  2060. and because of new flash mapping capabilities the flash-mapped regions
  2061. can be placed in the normal image (just @ 64kB padded offsets).
  2062. """
  2063. ROM_LOADER = ESP32ROM
  2064. # ROM bootloader will read the wp_pin field if SPI flash
  2065. # pins are remapped via flash. IDF actually enables QIO only
  2066. # from software bootloader, so this can be ignored. But needs
  2067. # to be set to this value so ROM bootloader will skip it.
  2068. WP_PIN_DISABLED = 0xEE
  2069. EXTENDED_HEADER_STRUCT_FMT = "<BBBBHB" + ("B" * 8) + "B"
  2070. IROM_ALIGN = 65536
  2071. def __init__(self, load_file=None):
  2072. super(ESP32FirmwareImage, self).__init__()
  2073. self.secure_pad = None
  2074. self.flash_mode = 0
  2075. self.flash_size_freq = 0
  2076. self.version = 1
  2077. self.wp_pin = self.WP_PIN_DISABLED
  2078. # SPI pin drive levels
  2079. self.clk_drv = 0
  2080. self.q_drv = 0
  2081. self.d_drv = 0
  2082. self.cs_drv = 0
  2083. self.hd_drv = 0
  2084. self.wp_drv = 0
  2085. self.min_rev = 0
  2086. self.append_digest = True
  2087. if load_file is not None:
  2088. start = load_file.tell()
  2089. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  2090. self.load_extended_header(load_file)
  2091. for _ in range(segments):
  2092. self.load_segment(load_file)
  2093. self.checksum = self.read_checksum(load_file)
  2094. if self.append_digest:
  2095. end = load_file.tell()
  2096. self.stored_digest = load_file.read(32)
  2097. load_file.seek(start)
  2098. calc_digest = hashlib.sha256()
  2099. calc_digest.update(load_file.read(end - start))
  2100. self.calc_digest = calc_digest.digest() # TODO: decide what to do here?
  2101. self.verify()
  2102. def is_flash_addr(self, addr):
  2103. return (self.ROM_LOADER.IROM_MAP_START <= addr < self.ROM_LOADER.IROM_MAP_END) \
  2104. or (self.ROM_LOADER.DROM_MAP_START <= addr < self.ROM_LOADER.DROM_MAP_END)
  2105. def default_output_name(self, input_file):
  2106. """ Derive a default output name from the ELF name. """
  2107. return "%s.bin" % (os.path.splitext(input_file)[0])
  2108. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  2109. pass # TODO: add warnings for ESP32 segment offset/size combinations that are wrong
  2110. def save(self, filename):
  2111. total_segments = 0
  2112. with io.BytesIO() as f: # write file to memory first
  2113. self.write_common_header(f, self.segments)
  2114. # first 4 bytes of header are read by ROM bootloader for SPI
  2115. # config, but currently unused
  2116. self.save_extended_header(f)
  2117. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  2118. # split segments into flash-mapped vs ram-loaded, and take copies so we can mutate them
  2119. flash_segments = [copy.deepcopy(s) for s in sorted(self.segments, key=lambda s:s.addr) if self.is_flash_addr(s.addr)]
  2120. ram_segments = [copy.deepcopy(s) for s in sorted(self.segments, key=lambda s:s.addr) if not self.is_flash_addr(s.addr)]
  2121. # check for multiple ELF sections that are mapped in the same flash mapping region.
  2122. # this is usually a sign of a broken linker script, but if you have a legitimate
  2123. # use case then let us know
  2124. if len(flash_segments) > 0:
  2125. last_addr = flash_segments[0].addr
  2126. for segment in flash_segments[1:]:
  2127. if segment.addr // self.IROM_ALIGN == last_addr // self.IROM_ALIGN:
  2128. raise FatalError(("Segment loaded at 0x%08x lands in same 64KB flash mapping as segment loaded at 0x%08x. "
  2129. "Can't generate binary. Suggest changing linker script or ELF to merge sections.") %
  2130. (segment.addr, last_addr))
  2131. last_addr = segment.addr
  2132. def get_alignment_data_needed(segment):
  2133. # Actual alignment (in data bytes) required for a segment header: positioned so that
  2134. # after we write the next 8 byte header, file_offs % IROM_ALIGN == segment.addr % IROM_ALIGN
  2135. #
  2136. # (this is because the segment's vaddr may not be IROM_ALIGNed, more likely is aligned
  2137. # IROM_ALIGN+0x18 to account for the binary file header
  2138. align_past = (segment.addr % self.IROM_ALIGN) - self.SEG_HEADER_LEN
  2139. pad_len = (self.IROM_ALIGN - (f.tell() % self.IROM_ALIGN)) + align_past
  2140. if pad_len == 0 or pad_len == self.IROM_ALIGN:
  2141. return 0 # already aligned
  2142. # subtract SEG_HEADER_LEN a second time, as the padding block has a header as well
  2143. pad_len -= self.SEG_HEADER_LEN
  2144. if pad_len < 0:
  2145. pad_len += self.IROM_ALIGN
  2146. return pad_len
  2147. # try to fit each flash segment on a 64kB aligned boundary
  2148. # by padding with parts of the non-flash segments...
  2149. while len(flash_segments) > 0:
  2150. segment = flash_segments[0]
  2151. pad_len = get_alignment_data_needed(segment)
  2152. if pad_len > 0: # need to pad
  2153. if len(ram_segments) > 0 and pad_len > self.SEG_HEADER_LEN:
  2154. pad_segment = ram_segments[0].split_image(pad_len)
  2155. if len(ram_segments[0].data) == 0:
  2156. ram_segments.pop(0)
  2157. else:
  2158. pad_segment = ImageSegment(0, b'\x00' * pad_len, f.tell())
  2159. checksum = self.save_segment(f, pad_segment, checksum)
  2160. total_segments += 1
  2161. else:
  2162. # write the flash segment
  2163. assert (f.tell() + 8) % self.IROM_ALIGN == segment.addr % self.IROM_ALIGN
  2164. checksum = self.save_flash_segment(f, segment, checksum)
  2165. flash_segments.pop(0)
  2166. total_segments += 1
  2167. # flash segments all written, so write any remaining RAM segments
  2168. for segment in ram_segments:
  2169. checksum = self.save_segment(f, segment, checksum)
  2170. total_segments += 1
  2171. if self.secure_pad:
  2172. # pad the image so that after signing it will end on a a 64KB boundary.
  2173. # This ensures all mapped flash content will be verified.
  2174. if not self.append_digest:
  2175. raise FatalError("secure_pad only applies if a SHA-256 digest is also appended to the image")
  2176. align_past = (f.tell() + self.SEG_HEADER_LEN) % self.IROM_ALIGN
  2177. # 16 byte aligned checksum (force the alignment to simplify calculations)
  2178. checksum_space = 16
  2179. if self.secure_pad == '1':
  2180. # after checksum: SHA-256 digest + (to be added by signing process) version, signature + 12 trailing bytes due to alignment
  2181. space_after_checksum = 32 + 4 + 64 + 12
  2182. elif self.secure_pad == '2': # Secure Boot V2
  2183. # after checksum: SHA-256 digest + signature sector, but we place signature sector after the 64KB boundary
  2184. space_after_checksum = 32
  2185. pad_len = (self.IROM_ALIGN - align_past - checksum_space - space_after_checksum) % self.IROM_ALIGN
  2186. pad_segment = ImageSegment(0, b'\x00' * pad_len, f.tell())
  2187. checksum = self.save_segment(f, pad_segment, checksum)
  2188. total_segments += 1
  2189. # done writing segments
  2190. self.append_checksum(f, checksum)
  2191. image_length = f.tell()
  2192. if self.secure_pad:
  2193. assert ((image_length + space_after_checksum) % self.IROM_ALIGN) == 0
  2194. # kinda hacky: go back to the initial header and write the new segment count
  2195. # that includes padding segments. This header is not checksummed
  2196. f.seek(1)
  2197. try:
  2198. f.write(chr(total_segments))
  2199. except TypeError: # Python 3
  2200. f.write(bytes([total_segments]))
  2201. if self.append_digest:
  2202. # calculate the SHA256 of the whole file and append it
  2203. f.seek(0)
  2204. digest = hashlib.sha256()
  2205. digest.update(f.read(image_length))
  2206. f.write(digest.digest())
  2207. with open(filename, 'wb') as real_file:
  2208. real_file.write(f.getvalue())
  2209. def save_flash_segment(self, f, segment, checksum=None):
  2210. """ Save the next segment to the image file, return next checksum value if provided """
  2211. segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN
  2212. segment_len_remainder = segment_end_pos % self.IROM_ALIGN
  2213. if segment_len_remainder < 0x24:
  2214. # Work around a bug in ESP-IDF 2nd stage bootloader, that it didn't map the
  2215. # last MMU page, if an IROM/DROM segment was < 0x24 bytes over the page boundary.
  2216. segment.data += b'\x00' * (0x24 - segment_len_remainder)
  2217. return self.save_segment(f, segment, checksum)
  2218. def load_extended_header(self, load_file):
  2219. def split_byte(n):
  2220. return (n & 0x0F, (n >> 4) & 0x0F)
  2221. fields = list(struct.unpack(self.EXTENDED_HEADER_STRUCT_FMT, load_file.read(16)))
  2222. self.wp_pin = fields[0]
  2223. # SPI pin drive stengths are two per byte
  2224. self.clk_drv, self.q_drv = split_byte(fields[1])
  2225. self.d_drv, self.cs_drv = split_byte(fields[2])
  2226. self.hd_drv, self.wp_drv = split_byte(fields[3])
  2227. chip_id = fields[4]
  2228. if chip_id != self.ROM_LOADER.IMAGE_CHIP_ID:
  2229. print(("Unexpected chip id in image. Expected %d but value was %d. "
  2230. "Is this image for a different chip model?") % (self.ROM_LOADER.IMAGE_CHIP_ID, chip_id))
  2231. # reserved fields in the middle should all be zero
  2232. if any(f for f in fields[6:-1] if f != 0):
  2233. print("Warning: some reserved header fields have non-zero values. This image may be from a newer esptool.py?")
  2234. append_digest = fields[-1] # last byte is append_digest
  2235. if append_digest in [0, 1]:
  2236. self.append_digest = (append_digest == 1)
  2237. else:
  2238. raise RuntimeError("Invalid value for append_digest field (0x%02x). Should be 0 or 1.", append_digest)
  2239. def save_extended_header(self, save_file):
  2240. def join_byte(ln, hn):
  2241. return (ln & 0x0F) + ((hn & 0x0F) << 4)
  2242. append_digest = 1 if self.append_digest else 0
  2243. fields = [self.wp_pin,
  2244. join_byte(self.clk_drv, self.q_drv),
  2245. join_byte(self.d_drv, self.cs_drv),
  2246. join_byte(self.hd_drv, self.wp_drv),
  2247. self.ROM_LOADER.IMAGE_CHIP_ID,
  2248. self.min_rev]
  2249. fields += [0] * 8 # padding
  2250. fields += [append_digest]
  2251. packed = struct.pack(self.EXTENDED_HEADER_STRUCT_FMT, *fields)
  2252. save_file.write(packed)
  2253. ESP32ROM.BOOTLOADER_IMAGE = ESP32FirmwareImage
  2254. class ESP32S2FirmwareImage(ESP32FirmwareImage):
  2255. """ ESP32S2 Firmware Image almost exactly the same as ESP32FirmwareImage """
  2256. ROM_LOADER = ESP32S2ROM
  2257. ESP32S2ROM.BOOTLOADER_IMAGE = ESP32S2FirmwareImage
  2258. class ESP32S3BETA2FirmwareImage(ESP32FirmwareImage):
  2259. """ ESP32S3 Firmware Image almost exactly the same as ESP32FirmwareImage """
  2260. ROM_LOADER = ESP32S3BETA2ROM
  2261. ESP32S3BETA2ROM.BOOTLOADER_IMAGE = ESP32S3BETA2FirmwareImage
  2262. class ESP32S3BETA3FirmwareImage(ESP32FirmwareImage):
  2263. """ ESP32S3 Firmware Image almost exactly the same as ESP32FirmwareImage """
  2264. ROM_LOADER = ESP32S3BETA3ROM
  2265. ESP32S3BETA3ROM.BOOTLOADER_IMAGE = ESP32S3BETA3FirmwareImage
  2266. class ESP32C3FirmwareImage(ESP32FirmwareImage):
  2267. """ ESP32C3 Firmware Image almost exactly the same as ESP32FirmwareImage """
  2268. ROM_LOADER = ESP32C3ROM
  2269. ESP32C3ROM.BOOTLOADER_IMAGE = ESP32C3FirmwareImage
  2270. class ELFFile(object):
  2271. SEC_TYPE_PROGBITS = 0x01
  2272. SEC_TYPE_STRTAB = 0x03
  2273. LEN_SEC_HEADER = 0x28
  2274. SEG_TYPE_LOAD = 0x01
  2275. LEN_SEG_HEADER = 0x20
  2276. def __init__(self, name):
  2277. # Load sections from the ELF file
  2278. self.name = name
  2279. with open(self.name, 'rb') as f:
  2280. self._read_elf_file(f)
  2281. def get_section(self, section_name):
  2282. for s in self.sections:
  2283. if s.name == section_name:
  2284. return s
  2285. raise ValueError("No section %s in ELF file" % section_name)
  2286. def _read_elf_file(self, f):
  2287. # read the ELF file header
  2288. LEN_FILE_HEADER = 0x34
  2289. try:
  2290. (ident, _type, machine, _version,
  2291. self.entrypoint, _phoff, shoff, _flags,
  2292. _ehsize, _phentsize, _phnum, shentsize,
  2293. shnum, shstrndx) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
  2294. except struct.error as e:
  2295. raise FatalError("Failed to read a valid ELF header from %s: %s" % (self.name, e))
  2296. if byte(ident, 0) != 0x7f or ident[1:4] != b'ELF':
  2297. raise FatalError("%s has invalid ELF magic header" % self.name)
  2298. if machine not in [0x5e, 0xf3]:
  2299. raise FatalError("%s does not appear to be an Xtensa or an RISCV ELF file. e_machine=%04x" % (self.name, machine))
  2300. if shentsize != self.LEN_SEC_HEADER:
  2301. raise FatalError("%s has unexpected section header entry size 0x%x (not 0x%x)" % (self.name, shentsize, self.LEN_SEC_HEADER))
  2302. if shnum == 0:
  2303. raise FatalError("%s has 0 section headers" % (self.name))
  2304. self._read_sections(f, shoff, shnum, shstrndx)
  2305. self._read_segments(f, _phoff, _phnum, shstrndx)
  2306. def _read_sections(self, f, section_header_offs, section_header_count, shstrndx):
  2307. f.seek(section_header_offs)
  2308. len_bytes = section_header_count * self.LEN_SEC_HEADER
  2309. section_header = f.read(len_bytes)
  2310. if len(section_header) == 0:
  2311. raise FatalError("No section header found at offset %04x in ELF file." % section_header_offs)
  2312. if len(section_header) != (len_bytes):
  2313. raise FatalError("Only read 0x%x bytes from section header (expected 0x%x.) Truncated ELF file?" % (len(section_header), len_bytes))
  2314. # walk through the section header and extract all sections
  2315. section_header_offsets = range(0, len(section_header), self.LEN_SEC_HEADER)
  2316. def read_section_header(offs):
  2317. name_offs, sec_type, _flags, lma, sec_offs, size = struct.unpack_from("<LLLLLL", section_header[offs:])
  2318. return (name_offs, sec_type, lma, size, sec_offs)
  2319. all_sections = [read_section_header(offs) for offs in section_header_offsets]
  2320. prog_sections = [s for s in all_sections if s[1] == ELFFile.SEC_TYPE_PROGBITS]
  2321. # search for the string table section
  2322. if not (shstrndx * self.LEN_SEC_HEADER) in section_header_offsets:
  2323. raise FatalError("ELF file has no STRTAB section at shstrndx %d" % shstrndx)
  2324. _, sec_type, _, sec_size, sec_offs = read_section_header(shstrndx * self.LEN_SEC_HEADER)
  2325. if sec_type != ELFFile.SEC_TYPE_STRTAB:
  2326. print('WARNING: ELF file has incorrect STRTAB section type 0x%02x' % sec_type)
  2327. f.seek(sec_offs)
  2328. string_table = f.read(sec_size)
  2329. # build the real list of ELFSections by reading the actual section names from the
  2330. # string table section, and actual data for each section from the ELF file itself
  2331. def lookup_string(offs):
  2332. raw = string_table[offs:]
  2333. return raw[:raw.index(b'\x00')]
  2334. def read_data(offs, size):
  2335. f.seek(offs)
  2336. return f.read(size)
  2337. prog_sections = [ELFSection(lookup_string(n_offs), lma, read_data(offs, size)) for (n_offs, _type, lma, size, offs) in prog_sections
  2338. if lma != 0 and size > 0]
  2339. self.sections = prog_sections
  2340. def _read_segments(self, f, segment_header_offs, segment_header_count, shstrndx):
  2341. f.seek(segment_header_offs)
  2342. len_bytes = segment_header_count * self.LEN_SEG_HEADER
  2343. segment_header = f.read(len_bytes)
  2344. if len(segment_header) == 0:
  2345. raise FatalError("No segment header found at offset %04x in ELF file." % segment_header_offs)
  2346. if len(segment_header) != (len_bytes):
  2347. raise FatalError("Only read 0x%x bytes from segment header (expected 0x%x.) Truncated ELF file?" % (len(segment_header), len_bytes))
  2348. # walk through the segment header and extract all segments
  2349. segment_header_offsets = range(0, len(segment_header), self.LEN_SEG_HEADER)
  2350. def read_segment_header(offs):
  2351. seg_type, seg_offs, _vaddr, lma, size, _memsize, _flags, _align = struct.unpack_from("<LLLLLLLL", segment_header[offs:])
  2352. return (seg_type, lma, size, seg_offs)
  2353. all_segments = [read_segment_header(offs) for offs in segment_header_offsets]
  2354. prog_segments = [s for s in all_segments if s[0] == ELFFile.SEG_TYPE_LOAD]
  2355. def read_data(offs, size):
  2356. f.seek(offs)
  2357. return f.read(size)
  2358. prog_segments = [ELFSection(b'PHDR', lma, read_data(offs, size)) for (_type, lma, size, offs) in prog_segments
  2359. if lma != 0 and size > 0]
  2360. self.segments = prog_segments
  2361. def sha256(self):
  2362. # return SHA256 hash of the input ELF file
  2363. sha256 = hashlib.sha256()
  2364. with open(self.name, 'rb') as f:
  2365. sha256.update(f.read())
  2366. return sha256.digest()
  2367. def slip_reader(port, trace_function):
  2368. """Generator to read SLIP packets from a serial port.
  2369. Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
  2370. Designed to avoid too many calls to serial.read(1), which can bog
  2371. down on slow systems.
  2372. """
  2373. partial_packet = None
  2374. in_escape = False
  2375. while True:
  2376. waiting = port.inWaiting()
  2377. read_bytes = port.read(1 if waiting == 0 else waiting)
  2378. if read_bytes == b'':
  2379. waiting_for = "header" if partial_packet is None else "content"
  2380. trace_function("Timed out waiting for packet %s", waiting_for)
  2381. raise FatalError("Timed out waiting for packet %s" % waiting_for)
  2382. trace_function("Read %d bytes: %s", len(read_bytes), HexFormatter(read_bytes))
  2383. for b in read_bytes:
  2384. if type(b) is int:
  2385. b = bytes([b]) # python 2/3 compat
  2386. if partial_packet is None: # waiting for packet header
  2387. if b == b'\xc0':
  2388. partial_packet = b""
  2389. else:
  2390. trace_function("Read invalid data: %s", HexFormatter(read_bytes))
  2391. trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting())))
  2392. raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
  2393. elif in_escape: # part-way through escape sequence
  2394. in_escape = False
  2395. if b == b'\xdc':
  2396. partial_packet += b'\xc0'
  2397. elif b == b'\xdd':
  2398. partial_packet += b'\xdb'
  2399. else:
  2400. trace_function("Read invalid data: %s", HexFormatter(read_bytes))
  2401. trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting())))
  2402. raise FatalError('Invalid SLIP escape (0xdb, 0x%s)' % (hexify(b)))
  2403. elif b == b'\xdb': # start of escape sequence
  2404. in_escape = True
  2405. elif b == b'\xc0': # end of packet
  2406. trace_function("Received full packet: %s", HexFormatter(partial_packet))
  2407. yield partial_packet
  2408. partial_packet = None
  2409. else: # normal byte in packet
  2410. partial_packet += b
  2411. def arg_auto_int(x):
  2412. return int(x, 0)
  2413. def div_roundup(a, b):
  2414. """ Return a/b rounded up to nearest integer,
  2415. equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
  2416. without possible floating point accuracy errors.
  2417. """
  2418. return (int(a) + int(b) - 1) // int(b)
  2419. def align_file_position(f, size):
  2420. """ Align the position in the file to the next block of specified size """
  2421. align = (size - 1) - (f.tell() % size)
  2422. f.seek(align, 1)
  2423. def flash_size_bytes(size):
  2424. """ Given a flash size of the type passed in args.flash_size
  2425. (ie 512KB or 1MB) then return the size in bytes.
  2426. """
  2427. if "MB" in size:
  2428. return int(size[:size.index("MB")]) * 1024 * 1024
  2429. elif "KB" in size:
  2430. return int(size[:size.index("KB")]) * 1024
  2431. else:
  2432. raise FatalError("Unknown size %s" % size)
  2433. def hexify(s, uppercase=True):
  2434. format_str = '%02X' if uppercase else '%02x'
  2435. if not PYTHON2:
  2436. return ''.join(format_str % c for c in s)
  2437. else:
  2438. return ''.join(format_str % ord(c) for c in s)
  2439. class HexFormatter(object):
  2440. """
  2441. Wrapper class which takes binary data in its constructor
  2442. and returns a hex string as it's __str__ method.
  2443. This is intended for "lazy formatting" of trace() output
  2444. in hex format. Avoids overhead (significant on slow computers)
  2445. of generating long hex strings even if tracing is disabled.
  2446. Note that this doesn't save any overhead if passed as an
  2447. argument to "%", only when passed to trace()
  2448. If auto_split is set (default), any long line (> 16 bytes) will be
  2449. printed as separately indented lines, with ASCII decoding at the end
  2450. of each line.
  2451. """
  2452. def __init__(self, binary_string, auto_split=True):
  2453. self._s = binary_string
  2454. self._auto_split = auto_split
  2455. def __str__(self):
  2456. if self._auto_split and len(self._s) > 16:
  2457. result = ""
  2458. s = self._s
  2459. while len(s) > 0:
  2460. line = s[:16]
  2461. ascii_line = "".join(c if (c == ' ' or (c in string.printable and c not in string.whitespace))
  2462. else '.' for c in line.decode('ascii', 'replace'))
  2463. s = s[16:]
  2464. result += "\n %-16s %-16s | %s" % (hexify(line[:8], False), hexify(line[8:], False), ascii_line)
  2465. return result
  2466. else:
  2467. return hexify(self._s, False)
  2468. def pad_to(data, alignment, pad_character=b'\xFF'):
  2469. """ Pad to the next alignment boundary """
  2470. pad_mod = len(data) % alignment
  2471. if pad_mod != 0:
  2472. data += pad_character * (alignment - pad_mod)
  2473. return data
  2474. class FatalError(RuntimeError):
  2475. """
  2476. Wrapper class for runtime errors that aren't caused by internal bugs, but by
  2477. ESP8266 responses or input content.
  2478. """
  2479. def __init__(self, message):
  2480. RuntimeError.__init__(self, message)
  2481. @staticmethod
  2482. def WithResult(message, result):
  2483. """
  2484. Return a fatal error object that appends the hex values of
  2485. 'result' as a string formatted argument.
  2486. """
  2487. message += " (result was %s)" % hexify(result)
  2488. return FatalError(message)
  2489. class NotImplementedInROMError(FatalError):
  2490. """
  2491. Wrapper class for the error thrown when a particular ESP bootloader function
  2492. is not implemented in the ROM bootloader.
  2493. """
  2494. def __init__(self, bootloader, func):
  2495. FatalError.__init__(self, "%s ROM does not support function %s." % (bootloader.CHIP_NAME, func.__name__))
  2496. class NotSupportedError(FatalError):
  2497. def __init__(self, esp, function_name):
  2498. FatalError.__init__(self, "Function %s is not supported for %s." % (function_name, esp.CHIP_NAME))
  2499. # "Operation" commands, executable at command line. One function each
  2500. #
  2501. # Each function takes either two args (<ESPLoader instance>, <args>) or a single <args>
  2502. # argument.
  2503. class UnsupportedCommandError(RuntimeError):
  2504. """
  2505. Wrapper class for when ROM loader returns an invalid command response.
  2506. Usually this indicates the loader is running in Secure Download Mode.
  2507. """
  2508. def __init__(self, esp, op):
  2509. if esp.secure_download_mode:
  2510. msg = "This command (0x%x) is not supported in Secure Download Mode" % op
  2511. else:
  2512. msg = "Invalid (unsupported) command 0x%x" % op
  2513. RuntimeError.__init__(self, msg)
  2514. def load_ram(esp, args):
  2515. image = LoadFirmwareImage(esp.CHIP_NAME, args.filename)
  2516. print('RAM boot...')
  2517. for seg in image.segments:
  2518. size = len(seg.data)
  2519. print('Downloading %d bytes at %08x...' % (size, seg.addr), end=' ')
  2520. sys.stdout.flush()
  2521. esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, seg.addr)
  2522. seq = 0
  2523. while len(seg.data) > 0:
  2524. esp.mem_block(seg.data[0:esp.ESP_RAM_BLOCK], seq)
  2525. seg.data = seg.data[esp.ESP_RAM_BLOCK:]
  2526. seq += 1
  2527. print('done!')
  2528. print('All segments done, executing at %08x' % image.entrypoint)
  2529. esp.mem_finish(image.entrypoint)
  2530. def read_mem(esp, args):
  2531. print('0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address)))
  2532. def write_mem(esp, args):
  2533. esp.write_reg(args.address, args.value, args.mask, 0)
  2534. print('Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address))
  2535. def dump_mem(esp, args):
  2536. with open(args.filename, 'wb') as f:
  2537. for i in range(args.size // 4):
  2538. d = esp.read_reg(args.address + (i * 4))
  2539. f.write(struct.pack(b'<I', d))
  2540. if f.tell() % 1024 == 0:
  2541. print_overwrite('%d bytes read... (%d %%)' % (f.tell(),
  2542. f.tell() * 100 // args.size))
  2543. sys.stdout.flush()
  2544. print_overwrite("Read %d bytes" % f.tell(), last_line=True)
  2545. print('Done!')
  2546. def detect_flash_size(esp, args):
  2547. if args.flash_size == 'detect':
  2548. if esp.secure_download_mode:
  2549. raise FatalError("Detecting flash size is not supported in secure download mode. Need to manually specify flash size.")
  2550. flash_id = esp.flash_id()
  2551. size_id = flash_id >> 16
  2552. args.flash_size = DETECTED_FLASH_SIZES.get(size_id)
  2553. if args.flash_size is None:
  2554. print('Warning: Could not auto-detect Flash size (FlashID=0x%x, SizeID=0x%x), defaulting to 4MB' % (flash_id, size_id))
  2555. args.flash_size = '4MB'
  2556. else:
  2557. print('Auto-detected Flash size:', args.flash_size)
  2558. def _update_image_flash_params(esp, address, args, image):
  2559. """ Modify the flash mode & size bytes if this looks like an executable bootloader image """
  2560. if len(image) < 8:
  2561. return image # not long enough to be a bootloader image
  2562. # unpack the (potential) image header
  2563. magic, _, flash_mode, flash_size_freq = struct.unpack("BBBB", image[:4])
  2564. if address != esp.BOOTLOADER_FLASH_OFFSET:
  2565. return image # not flashing bootloader offset, so don't modify this
  2566. if (args.flash_mode, args.flash_freq, args.flash_size) == ('keep',) * 3:
  2567. return image # all settings are 'keep', not modifying anything
  2568. # easy check if this is an image: does it start with a magic byte?
  2569. if magic != esp.ESP_IMAGE_MAGIC:
  2570. print("Warning: Image file at 0x%x doesn't look like an image file, so not changing any flash settings." % address)
  2571. return image
  2572. # make sure this really is an image, and not just data that
  2573. # starts with esp.ESP_IMAGE_MAGIC (mostly a problem for encrypted
  2574. # images that happen to start with a magic byte
  2575. try:
  2576. test_image = esp.BOOTLOADER_IMAGE(io.BytesIO(image))
  2577. test_image.verify()
  2578. except Exception:
  2579. print("Warning: Image file at 0x%x is not a valid %s image, so not changing any flash settings." % (address, esp.CHIP_NAME))
  2580. return image
  2581. if args.flash_mode != 'keep':
  2582. flash_mode = {'qio': 0, 'qout': 1, 'dio': 2, 'dout': 3}[args.flash_mode]
  2583. flash_freq = flash_size_freq & 0x0F
  2584. if args.flash_freq != 'keep':
  2585. flash_freq = {'40m': 0, '26m': 1, '20m': 2, '80m': 0xf}[args.flash_freq]
  2586. flash_size = flash_size_freq & 0xF0
  2587. if args.flash_size != 'keep':
  2588. flash_size = esp.parse_flash_size_arg(args.flash_size)
  2589. flash_params = struct.pack(b'BB', flash_mode, flash_size + flash_freq)
  2590. if flash_params != image[2:4]:
  2591. print('Flash params set to 0x%04x' % struct.unpack(">H", flash_params))
  2592. image = image[0:2] + flash_params + image[4:]
  2593. return image
  2594. def write_flash(esp, args):
  2595. # set args.compress based on default behaviour:
  2596. # -> if either --compress or --no-compress is set, honour that
  2597. # -> otherwise, set --compress unless --no-stub is set
  2598. if args.compress is None and not args.no_compress:
  2599. args.compress = not args.no_stub
  2600. # In case we have encrypted files to write, we first do few sanity checks before actual flash
  2601. if args.encrypt or args.encrypt_files is not None:
  2602. do_write = True
  2603. if not esp.secure_download_mode:
  2604. if esp.get_encrypted_download_disabled():
  2605. raise FatalError("This chip has encrypt functionality in UART download mode disabled. "
  2606. "This is the Flash Encryption configuration for Production mode instead of Development mode.")
  2607. crypt_cfg_efuse = esp.get_flash_crypt_config()
  2608. if crypt_cfg_efuse is not None and crypt_cfg_efuse != 0xF:
  2609. print('Unexpected FLASH_CRYPT_CONFIG value: 0x%x' % (crypt_cfg_efuse))
  2610. do_write = False
  2611. enc_key_valid = esp.is_flash_encryption_key_valid()
  2612. if not enc_key_valid:
  2613. print('Flash encryption key is not programmed')
  2614. do_write = False
  2615. # Determine which files list contain the ones to encrypt
  2616. files_to_encrypt = args.addr_filename if args.encrypt else args.encrypt_files
  2617. for address, argfile in files_to_encrypt:
  2618. if address % esp.FLASH_ENCRYPTED_WRITE_ALIGN:
  2619. print("File %s address 0x%x is not %d byte aligned, can't flash encrypted" %
  2620. (argfile.name, address, esp.FLASH_ENCRYPTED_WRITE_ALIGN))
  2621. do_write = False
  2622. if not do_write and not args.ignore_flash_encryption_efuse_setting:
  2623. raise FatalError("Can't perform encrypted flash write, consult Flash Encryption documentation for more information")
  2624. # verify file sizes fit in flash
  2625. if args.flash_size != 'keep': # TODO: check this even with 'keep'
  2626. flash_end = flash_size_bytes(args.flash_size)
  2627. for address, argfile in args.addr_filename:
  2628. argfile.seek(0, 2) # seek to end
  2629. if address + argfile.tell() > flash_end:
  2630. raise FatalError(("File %s (length %d) at offset %d will not fit in %d bytes of flash. "
  2631. "Use --flash-size argument, or change flashing address.")
  2632. % (argfile.name, argfile.tell(), address, flash_end))
  2633. argfile.seek(0)
  2634. if args.erase_all:
  2635. erase_flash(esp, args)
  2636. """ Create a list describing all the files we have to flash. Each entry holds an "encrypt" flag
  2637. marking whether the file needs encryption or not. This list needs to be sorted.
  2638. First, append to each entry of our addr_filename list the flag args.encrypt
  2639. For example, if addr_filename is [(0x1000, "partition.bin"), (0x8000, "bootloader")],
  2640. all_files will be [(0x1000, "partition.bin", args.encrypt), (0x8000, "bootloader", args.encrypt)],
  2641. where, of course, args.encrypt is either True or False
  2642. """
  2643. all_files = [(offs, filename, args.encrypt) for (offs, filename) in args.addr_filename]
  2644. """Now do the same with encrypt_files list, if defined.
  2645. In this case, the flag is True
  2646. """
  2647. if args.encrypt_files is not None:
  2648. encrypted_files_flag = [(offs, filename, True) for (offs, filename) in args.encrypt_files]
  2649. # Concatenate both lists and sort them.
  2650. # As both list are already sorted, we could simply do a merge instead,
  2651. # but for the sake of simplicity and because the lists are very small,
  2652. # let's use sorted.
  2653. all_files = sorted(all_files + encrypted_files_flag, key=lambda x: x[0])
  2654. for address, argfile, encrypted in all_files:
  2655. compress = args.compress
  2656. # Check whether we can compress the current file before flashing
  2657. if compress and encrypted:
  2658. print('\nWARNING: - compress and encrypt options are mutually exclusive ')
  2659. print('Will flash %s uncompressed' % argfile.name)
  2660. compress = False
  2661. if args.no_stub:
  2662. print('Erasing flash...')
  2663. image = pad_to(argfile.read(), esp.FLASH_ENCRYPTED_WRITE_ALIGN if encrypted else 4)
  2664. if len(image) == 0:
  2665. print('WARNING: File %s is empty' % argfile.name)
  2666. continue
  2667. image = _update_image_flash_params(esp, address, args, image)
  2668. calcmd5 = hashlib.md5(image).hexdigest()
  2669. uncsize = len(image)
  2670. if compress:
  2671. uncimage = image
  2672. image = zlib.compress(uncimage, 9)
  2673. # Decompress the compressed binary a block at a time, to dynamically calculate the
  2674. # timeout based on the real write size
  2675. decompress = zlib.decompressobj()
  2676. blocks = esp.flash_defl_begin(uncsize, len(image), address)
  2677. else:
  2678. blocks = esp.flash_begin(uncsize, address, begin_rom_encrypted=encrypted)
  2679. argfile.seek(0) # in case we need it again
  2680. seq = 0
  2681. bytes_sent = 0 # bytes sent on wire
  2682. bytes_written = 0 # bytes written to flash
  2683. t = time.time()
  2684. timeout = DEFAULT_TIMEOUT
  2685. while len(image) > 0:
  2686. print_overwrite('Writing at 0x%08x... (%d %%)' % (address + bytes_written, 100 * (seq + 1) // blocks))
  2687. sys.stdout.flush()
  2688. block = image[0:esp.FLASH_WRITE_SIZE]
  2689. if compress:
  2690. # feeding each compressed block into the decompressor lets us see block-by-block how much will be written
  2691. block_uncompressed = len(decompress.decompress(block))
  2692. bytes_written += block_uncompressed
  2693. block_timeout = max(DEFAULT_TIMEOUT, timeout_per_mb(ERASE_WRITE_TIMEOUT_PER_MB, block_uncompressed))
  2694. if not esp.IS_STUB:
  2695. timeout = block_timeout # ROM code writes block to flash before ACKing
  2696. esp.flash_defl_block(block, seq, timeout=timeout)
  2697. if esp.IS_STUB:
  2698. timeout = block_timeout # Stub ACKs when block is received, then writes to flash while receiving the block after it
  2699. else:
  2700. # Pad the last block
  2701. block = block + b'\xff' * (esp.FLASH_WRITE_SIZE - len(block))
  2702. if encrypted:
  2703. esp.flash_encrypt_block(block, seq)
  2704. else:
  2705. esp.flash_block(block, seq)
  2706. bytes_written += len(block)
  2707. bytes_sent += len(block)
  2708. image = image[esp.FLASH_WRITE_SIZE:]
  2709. seq += 1
  2710. if esp.IS_STUB:
  2711. # Stub only writes each block to flash after 'ack'ing the receive, so do a final dummy operation which will
  2712. # not be 'ack'ed until the last block has actually been written out to flash
  2713. esp.read_reg(ESPLoader.CHIP_DETECT_MAGIC_REG_ADDR, timeout=timeout)
  2714. t = time.time() - t
  2715. speed_msg = ""
  2716. if compress:
  2717. if t > 0.0:
  2718. speed_msg = " (effective %.1f kbit/s)" % (uncsize / t * 8 / 1000)
  2719. print_overwrite('Wrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s...' % (uncsize,
  2720. bytes_sent,
  2721. address, t, speed_msg), last_line=True)
  2722. else:
  2723. if t > 0.0:
  2724. speed_msg = " (%.1f kbit/s)" % (bytes_written / t * 8 / 1000)
  2725. print_overwrite('Wrote %d bytes at 0x%08x in %.1f seconds%s...' % (bytes_written, address, t, speed_msg), last_line=True)
  2726. if not encrypted and not esp.secure_download_mode:
  2727. try:
  2728. res = esp.flash_md5sum(address, uncsize)
  2729. if res != calcmd5:
  2730. print('File md5: %s' % calcmd5)
  2731. print('Flash md5: %s' % res)
  2732. print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest()))
  2733. raise FatalError("MD5 of file does not match data in flash!")
  2734. else:
  2735. print('Hash of data verified.')
  2736. except NotImplementedInROMError:
  2737. pass
  2738. print('\nLeaving...')
  2739. if esp.IS_STUB:
  2740. # skip sending flash_finish to ROM loader here,
  2741. # as it causes the loader to exit and run user code
  2742. esp.flash_begin(0, 0)
  2743. # Get the "encrypted" flag for the last file flashed
  2744. # Note: all_files list contains triplets like:
  2745. # (address: Integer, filename: String, encrypted: Boolean)
  2746. last_file_encrypted = all_files[-1][2]
  2747. # Check whether the last file flashed was compressed or not
  2748. if args.compress and not last_file_encrypted:
  2749. esp.flash_defl_finish(False)
  2750. else:
  2751. esp.flash_finish(False)
  2752. if args.verify:
  2753. print('Verifying just-written flash...')
  2754. print('(This option is deprecated, flash contents are now always read back after flashing.)')
  2755. # If some encrypted files have been flashed print a warning saying that we won't check them
  2756. if args.encrypt or args.encrypt_files is not None:
  2757. print('WARNING: - cannot verify encrypted files, they will be ignored')
  2758. # Call verify_flash function only if there at least one non-encrypted file flashed
  2759. if not args.encrypt:
  2760. verify_flash(esp, args)
  2761. def image_info(args):
  2762. image = LoadFirmwareImage(args.chip, args.filename)
  2763. print('Image version: %d' % image.version)
  2764. print('Entry point: %08x' % image.entrypoint if image.entrypoint != 0 else 'Entry point not set')
  2765. print('%d segments' % len(image.segments))
  2766. print()
  2767. idx = 0
  2768. for seg in image.segments:
  2769. idx += 1
  2770. segs = seg.get_memory_type(image)
  2771. seg_name = ",".join(segs)
  2772. print('Segment %d: %r [%s]' % (idx, seg, seg_name))
  2773. calc_checksum = image.calculate_checksum()
  2774. print('Checksum: %02x (%s)' % (image.checksum,
  2775. 'valid' if image.checksum == calc_checksum else 'invalid - calculated %02x' % calc_checksum))
  2776. try:
  2777. digest_msg = 'Not appended'
  2778. if image.append_digest:
  2779. is_valid = image.stored_digest == image.calc_digest
  2780. digest_msg = "%s (%s)" % (hexify(image.calc_digest).lower(),
  2781. "valid" if is_valid else "invalid")
  2782. print('Validation Hash: %s' % digest_msg)
  2783. except AttributeError:
  2784. pass # ESP8266 image has no append_digest field
  2785. def make_image(args):
  2786. image = ESP8266ROMFirmwareImage()
  2787. if len(args.segfile) == 0:
  2788. raise FatalError('No segments specified')
  2789. if len(args.segfile) != len(args.segaddr):
  2790. raise FatalError('Number of specified files does not match number of specified addresses')
  2791. for (seg, addr) in zip(args.segfile, args.segaddr):
  2792. with open(seg, 'rb') as f:
  2793. data = f.read()
  2794. image.segments.append(ImageSegment(addr, data))
  2795. image.entrypoint = args.entrypoint
  2796. image.save(args.output)
  2797. def elf2image(args):
  2798. e = ELFFile(args.input)
  2799. if args.chip == 'auto': # Default to ESP8266 for backwards compatibility
  2800. print("Creating image for ESP8266...")
  2801. args.chip = 'esp8266'
  2802. if args.chip == 'esp32':
  2803. image = ESP32FirmwareImage()
  2804. if args.secure_pad:
  2805. image.secure_pad = '1'
  2806. elif args.secure_pad_v2:
  2807. image.secure_pad = '2'
  2808. elif args.chip == 'esp32s2':
  2809. image = ESP32S2FirmwareImage()
  2810. if args.secure_pad_v2:
  2811. image.secure_pad = '2'
  2812. elif args.chip == 'esp32s3beta2':
  2813. image = ESP32S3BETA2FirmwareImage()
  2814. if args.secure_pad_v2:
  2815. image.secure_pad = '2'
  2816. elif args.chip == 'esp32s3beta3':
  2817. image = ESP32S3BETA3FirmwareImage()
  2818. if args.secure_pad_v2:
  2819. image.secure_pad = '2'
  2820. elif args.chip == 'esp32c3':
  2821. image = ESP32C3FirmwareImage()
  2822. if args.secure_pad_v2:
  2823. image.secure_pad = '2'
  2824. elif args.version == '1': # ESP8266
  2825. image = ESP8266ROMFirmwareImage()
  2826. else:
  2827. image = ESP8266V2FirmwareImage()
  2828. image.entrypoint = e.entrypoint
  2829. image.flash_mode = {'qio': 0, 'qout': 1, 'dio': 2, 'dout': 3}[args.flash_mode]
  2830. if args.chip != 'esp8266':
  2831. image.min_rev = int(args.min_rev)
  2832. # ELFSection is a subclass of ImageSegment, so can use interchangeably
  2833. image.segments = e.segments if args.use_segments else e.sections
  2834. image.flash_size_freq = image.ROM_LOADER.FLASH_SIZES[args.flash_size]
  2835. image.flash_size_freq += {'40m': 0, '26m': 1, '20m': 2, '80m': 0xf}[args.flash_freq]
  2836. if args.elf_sha256_offset:
  2837. image.elf_sha256 = e.sha256()
  2838. image.elf_sha256_offset = args.elf_sha256_offset
  2839. before = len(image.segments)
  2840. image.merge_adjacent_segments()
  2841. if len(image.segments) != before:
  2842. delta = before - len(image.segments)
  2843. print("Merged %d ELF section%s" % (delta, "s" if delta > 1 else ""))
  2844. image.verify()
  2845. if args.output is None:
  2846. args.output = image.default_output_name(args.input)
  2847. image.save(args.output)
  2848. def read_mac(esp, args):
  2849. mac = esp.read_mac()
  2850. def print_mac(label, mac):
  2851. print('%s: %s' % (label, ':'.join(map(lambda x: '%02x' % x, mac))))
  2852. print_mac("MAC", mac)
  2853. def chip_id(esp, args):
  2854. try:
  2855. chipid = esp.chip_id()
  2856. print('Chip ID: 0x%08x' % chipid)
  2857. except NotSupportedError:
  2858. print('Warning: %s has no Chip ID. Reading MAC instead.' % esp.CHIP_NAME)
  2859. read_mac(esp, args)
  2860. def erase_flash(esp, args):
  2861. print('Erasing flash (this may take a while)...')
  2862. t = time.time()
  2863. esp.erase_flash()
  2864. print('Chip erase completed successfully in %.1fs' % (time.time() - t))
  2865. def erase_region(esp, args):
  2866. print('Erasing region (may be slow depending on size)...')
  2867. t = time.time()
  2868. esp.erase_region(args.address, args.size)
  2869. print('Erase completed successfully in %.1f seconds.' % (time.time() - t))
  2870. def run(esp, args):
  2871. esp.run()
  2872. def flash_id(esp, args):
  2873. flash_id = esp.flash_id()
  2874. print('Manufacturer: %02x' % (flash_id & 0xff))
  2875. flid_lowbyte = (flash_id >> 16) & 0xFF
  2876. print('Device: %02x%02x' % ((flash_id >> 8) & 0xff, flid_lowbyte))
  2877. print('Detected flash size: %s' % (DETECTED_FLASH_SIZES.get(flid_lowbyte, "Unknown")))
  2878. def read_flash(esp, args):
  2879. if args.no_progress:
  2880. flash_progress = None
  2881. else:
  2882. def flash_progress(progress, length):
  2883. msg = '%d (%d %%)' % (progress, progress * 100.0 / length)
  2884. padding = '\b' * len(msg)
  2885. if progress == length:
  2886. padding = '\n'
  2887. sys.stdout.write(msg + padding)
  2888. sys.stdout.flush()
  2889. t = time.time()
  2890. data = esp.read_flash(args.address, args.size, flash_progress)
  2891. t = time.time() - t
  2892. print_overwrite('Read %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  2893. % (len(data), args.address, t, len(data) / t * 8 / 1000), last_line=True)
  2894. with open(args.filename, 'wb') as f:
  2895. f.write(data)
  2896. def verify_flash(esp, args):
  2897. differences = False
  2898. for address, argfile in args.addr_filename:
  2899. image = pad_to(argfile.read(), 4)
  2900. argfile.seek(0) # rewind in case we need it again
  2901. image = _update_image_flash_params(esp, address, args, image)
  2902. image_size = len(image)
  2903. print('Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name))
  2904. # Try digest first, only read if there are differences.
  2905. digest = esp.flash_md5sum(address, image_size)
  2906. expected_digest = hashlib.md5(image).hexdigest()
  2907. if digest == expected_digest:
  2908. print('-- verify OK (digest matched)')
  2909. continue
  2910. else:
  2911. differences = True
  2912. if getattr(args, 'diff', 'no') != 'yes':
  2913. print('-- verify FAILED (digest mismatch)')
  2914. continue
  2915. flash = esp.read_flash(address, image_size)
  2916. assert flash != image
  2917. diff = [i for i in range(image_size) if flash[i] != image[i]]
  2918. print('-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0]))
  2919. for d in diff:
  2920. flash_byte = flash[d]
  2921. image_byte = image[d]
  2922. if PYTHON2:
  2923. flash_byte = ord(flash_byte)
  2924. image_byte = ord(image_byte)
  2925. print(' %08x %02x %02x' % (address + d, flash_byte, image_byte))
  2926. if differences:
  2927. raise FatalError("Verify failed.")
  2928. def read_flash_status(esp, args):
  2929. print('Status value: 0x%04x' % esp.read_status(args.bytes))
  2930. def write_flash_status(esp, args):
  2931. fmt = "0x%%0%dx" % (args.bytes * 2)
  2932. args.value = args.value & ((1 << (args.bytes * 8)) - 1)
  2933. print(('Initial flash status: ' + fmt) % esp.read_status(args.bytes))
  2934. print(('Setting flash status: ' + fmt) % args.value)
  2935. esp.write_status(args.value, args.bytes, args.non_volatile)
  2936. print(('After flash status: ' + fmt) % esp.read_status(args.bytes))
  2937. def get_security_info(esp, args):
  2938. (flags, flash_crypt_cnt, key_purposes) = esp.get_security_info()
  2939. # TODO: better display
  2940. print('Flags: 0x%08x (%s)' % (flags, bin(flags)))
  2941. print('Flash_Crypt_Cnt: 0x%x' % flash_crypt_cnt)
  2942. print('Key_Purposes: %s' % (key_purposes,))
  2943. def merge_bin(args):
  2944. chip_class = _chip_to_rom_loader(args.chip)
  2945. # sort the files by offset. The AddrFilenamePairAction has already checked for overlap
  2946. input_files = sorted(args.addr_filename, key=lambda x: x[0])
  2947. if not input_files:
  2948. raise FatalError("No input files specified")
  2949. first_addr = input_files[0][0]
  2950. if first_addr < args.target_offset:
  2951. raise FatalError("Output file target offset is 0x%x. Input file offset 0x%x is before this." % (args.target_offset, first_addr))
  2952. if args.format != 'raw':
  2953. raise FatalError("This version of esptool only supports the 'raw' output format")
  2954. with open(args.output, 'wb') as of:
  2955. def pad_to(flash_offs):
  2956. # account for output file offset if there is any
  2957. of.write(b'\xFF' * (flash_offs - args.target_offset - of.tell()))
  2958. for addr, argfile in input_files:
  2959. pad_to(addr)
  2960. image = argfile.read()
  2961. image = _update_image_flash_params(chip_class, addr, args, image)
  2962. of.write(image)
  2963. if args.fill_flash_size:
  2964. pad_to(flash_size_bytes(args.fill_flash_size))
  2965. print("Wrote 0x%x bytes to file %s, ready to flash to offset 0x%x" % (of.tell(), args.output, args.target_offset))
  2966. def version(args):
  2967. print(__version__)
  2968. #
  2969. # End of operations functions
  2970. #
  2971. def main(argv=None, esp=None):
  2972. """
  2973. Main function for esptool
  2974. argv - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
  2975. as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
  2976. becomes ['-b', '115200'].
  2977. esp - Optional override of the connected device previously returned by get_default_connected_device()
  2978. """
  2979. external_esp = esp is not None
  2980. parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
  2981. parser.add_argument('--chip', '-c',
  2982. help='Target chip type',
  2983. type=lambda c: c.lower().replace('-', ''), # support ESP32-S2, etc.
  2984. choices=['auto', 'esp8266', 'esp32', 'esp32s2', 'esp32s3beta2', 'esp32s3beta3', 'esp32c3'],
  2985. default=os.environ.get('ESPTOOL_CHIP', 'auto'))
  2986. parser.add_argument(
  2987. '--port', '-p',
  2988. help='Serial port device',
  2989. default=os.environ.get('ESPTOOL_PORT', None))
  2990. parser.add_argument(
  2991. '--baud', '-b',
  2992. help='Serial port baud rate used when flashing/reading',
  2993. type=arg_auto_int,
  2994. default=os.environ.get('ESPTOOL_BAUD', ESPLoader.ESP_ROM_BAUD))
  2995. parser.add_argument(
  2996. '--before',
  2997. help='What to do before connecting to the chip',
  2998. choices=['default_reset', 'no_reset', 'no_reset_no_sync'],
  2999. default=os.environ.get('ESPTOOL_BEFORE', 'default_reset'))
  3000. parser.add_argument(
  3001. '--after', '-a',
  3002. help='What to do after esptool.py is finished',
  3003. choices=['hard_reset', 'soft_reset', 'no_reset'],
  3004. default=os.environ.get('ESPTOOL_AFTER', 'hard_reset'))
  3005. parser.add_argument(
  3006. '--no-stub',
  3007. help="Disable launching the flasher stub, only talk to ROM bootloader. Some features will not be available.",
  3008. action='store_true')
  3009. parser.add_argument(
  3010. '--trace', '-t',
  3011. help="Enable trace-level output of esptool.py interactions.",
  3012. action='store_true')
  3013. parser.add_argument(
  3014. '--override-vddsdio',
  3015. help="Override ESP32 VDDSDIO internal voltage regulator (use with care)",
  3016. choices=ESP32ROM.OVERRIDE_VDDSDIO_CHOICES,
  3017. nargs='?')
  3018. parser.add_argument(
  3019. '--connect-attempts',
  3020. help=('Number of attempts to connect, negative or 0 for infinite. '
  3021. 'Default: %d.' % DEFAULT_CONNECT_ATTEMPTS),
  3022. type=int,
  3023. default=os.environ.get('ESPTOOL_CONNECT_ATTEMPTS', DEFAULT_CONNECT_ATTEMPTS))
  3024. subparsers = parser.add_subparsers(
  3025. dest='operation',
  3026. help='Run esptool {command} -h for additional help')
  3027. def add_spi_connection_arg(parent):
  3028. parent.add_argument('--spi-connection', '-sc', help='ESP32-only argument. Override default SPI Flash connection. '
  3029. 'Value can be SPI, HSPI or a comma-separated list of 5 I/O numbers to use for SPI flash (CLK,Q,D,HD,CS).',
  3030. action=SpiConnectionAction)
  3031. parser_load_ram = subparsers.add_parser(
  3032. 'load_ram',
  3033. help='Download an image to RAM and execute')
  3034. parser_load_ram.add_argument('filename', help='Firmware image')
  3035. parser_dump_mem = subparsers.add_parser(
  3036. 'dump_mem',
  3037. help='Dump arbitrary memory to disk')
  3038. parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
  3039. parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  3040. parser_dump_mem.add_argument('filename', help='Name of binary dump')
  3041. parser_read_mem = subparsers.add_parser(
  3042. 'read_mem',
  3043. help='Read arbitrary memory location')
  3044. parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
  3045. parser_write_mem = subparsers.add_parser(
  3046. 'write_mem',
  3047. help='Read-modify-write to arbitrary memory location')
  3048. parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
  3049. parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
  3050. parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int, nargs='?', default='0xFFFFFFFF')
  3051. def add_spi_flash_subparsers(parent, allow_keep, auto_detect):
  3052. """ Add common parser arguments for SPI flash properties """
  3053. extra_keep_args = ['keep'] if allow_keep else []
  3054. if auto_detect and allow_keep:
  3055. extra_fs_message = ", detect, or keep"
  3056. elif auto_detect:
  3057. extra_fs_message = ", or detect"
  3058. elif allow_keep:
  3059. extra_fs_message = ", or keep"
  3060. else:
  3061. extra_fs_message = ""
  3062. parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
  3063. choices=extra_keep_args + ['40m', '26m', '20m', '80m'],
  3064. default=os.environ.get('ESPTOOL_FF', 'keep' if allow_keep else '40m'))
  3065. parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
  3066. choices=extra_keep_args + ['qio', 'qout', 'dio', 'dout'],
  3067. default=os.environ.get('ESPTOOL_FM', 'keep' if allow_keep else 'qio'))
  3068. parent.add_argument('--flash_size', '-fs', help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16M)'
  3069. ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1)' + extra_fs_message,
  3070. action=FlashSizeAction, auto_detect=auto_detect,
  3071. default=os.environ.get('ESPTOOL_FS', 'keep' if allow_keep else '1MB'))
  3072. add_spi_connection_arg(parent)
  3073. parser_write_flash = subparsers.add_parser(
  3074. 'write_flash',
  3075. help='Write a binary blob to flash')
  3076. parser_write_flash.add_argument('addr_filename', metavar='<address> <filename>', help='Address followed by binary filename, separated by space',
  3077. action=AddrFilenamePairAction)
  3078. parser_write_flash.add_argument('--erase-all', '-e',
  3079. help='Erase all regions of flash (not just write areas) before programming',
  3080. action="store_true")
  3081. add_spi_flash_subparsers(parser_write_flash, allow_keep=True, auto_detect=True)
  3082. parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  3083. parser_write_flash.add_argument('--verify', help='Verify just-written data on flash '
  3084. '(mostly superfluous, data is read back during flashing)', action='store_true')
  3085. parser_write_flash.add_argument('--encrypt', help='Apply flash encryption when writing data (required correct efuse settings)',
  3086. action='store_true')
  3087. # In order to not break backward compatibility, our list of encrypted files to flash is a new parameter
  3088. parser_write_flash.add_argument('--encrypt-files', metavar='<address> <filename>',
  3089. help='Files to be encrypted on the flash. Address followed by binary filename, separated by space.',
  3090. action=AddrFilenamePairAction)
  3091. parser_write_flash.add_argument('--ignore-flash-encryption-efuse-setting', help='Ignore flash encryption efuse settings ',
  3092. action='store_true')
  3093. compress_args = parser_write_flash.add_mutually_exclusive_group(required=False)
  3094. compress_args.add_argument('--compress', '-z', help='Compress data in transfer (default unless --no-stub is specified)',
  3095. action="store_true", default=None)
  3096. compress_args.add_argument('--no-compress', '-u', help='Disable data compression during transfer (default if --no-stub is specified)',
  3097. action="store_true")
  3098. subparsers.add_parser(
  3099. 'run',
  3100. help='Run application code in flash')
  3101. parser_image_info = subparsers.add_parser(
  3102. 'image_info',
  3103. help='Dump headers from an application image')
  3104. parser_image_info.add_argument('filename', help='Image file to parse')
  3105. parser_make_image = subparsers.add_parser(
  3106. 'make_image',
  3107. help='Create an application image from binary files')
  3108. parser_make_image.add_argument('output', help='Output image file')
  3109. parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
  3110. parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
  3111. parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
  3112. parser_elf2image = subparsers.add_parser(
  3113. 'elf2image',
  3114. help='Create an application image from ELF file')
  3115. parser_elf2image.add_argument('input', help='Input ELF file')
  3116. parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
  3117. parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1', '2'], default='1')
  3118. parser_elf2image.add_argument('--min-rev', '-r', help='Minimum chip revision', choices=['0', '1', '2', '3'], default='0')
  3119. parser_elf2image.add_argument('--secure-pad', action='store_true',
  3120. help='Pad image so once signed it will end on a 64KB boundary. For Secure Boot v1 images only.')
  3121. parser_elf2image.add_argument('--secure-pad-v2', action='store_true',
  3122. help='Pad image to 64KB, so once signed its signature sector will start at the next 64K block. '
  3123. 'For Secure Boot v2 images only.')
  3124. parser_elf2image.add_argument('--elf-sha256-offset', help='If set, insert SHA256 hash (32 bytes) of the input ELF file at specified offset in the binary.',
  3125. type=arg_auto_int, default=None)
  3126. parser_elf2image.add_argument('--use_segments', help='If set, ELF segments will be used instead of ELF sections to genereate the image.',
  3127. action='store_true')
  3128. add_spi_flash_subparsers(parser_elf2image, allow_keep=False, auto_detect=False)
  3129. subparsers.add_parser(
  3130. 'read_mac',
  3131. help='Read MAC address from OTP ROM')
  3132. subparsers.add_parser(
  3133. 'chip_id',
  3134. help='Read Chip ID from OTP ROM')
  3135. parser_flash_id = subparsers.add_parser(
  3136. 'flash_id',
  3137. help='Read SPI flash manufacturer and device ID')
  3138. add_spi_connection_arg(parser_flash_id)
  3139. parser_read_status = subparsers.add_parser(
  3140. 'read_flash_status',
  3141. help='Read SPI flash status register')
  3142. add_spi_connection_arg(parser_read_status)
  3143. parser_read_status.add_argument('--bytes', help='Number of bytes to read (1-3)', type=int, choices=[1, 2, 3], default=2)
  3144. parser_write_status = subparsers.add_parser(
  3145. 'write_flash_status',
  3146. help='Write SPI flash status register')
  3147. add_spi_connection_arg(parser_write_status)
  3148. parser_write_status.add_argument('--non-volatile', help='Write non-volatile bits (use with caution)', action='store_true')
  3149. parser_write_status.add_argument('--bytes', help='Number of status bytes to write (1-3)', type=int, choices=[1, 2, 3], default=2)
  3150. parser_write_status.add_argument('value', help='New value', type=arg_auto_int)
  3151. parser_read_flash = subparsers.add_parser(
  3152. 'read_flash',
  3153. help='Read SPI flash content')
  3154. add_spi_connection_arg(parser_read_flash)
  3155. parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
  3156. parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  3157. parser_read_flash.add_argument('filename', help='Name of binary dump')
  3158. parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  3159. parser_verify_flash = subparsers.add_parser(
  3160. 'verify_flash',
  3161. help='Verify a binary blob against flash')
  3162. parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
  3163. action=AddrFilenamePairAction)
  3164. parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
  3165. choices=['no', 'yes'], default='no')
  3166. add_spi_flash_subparsers(parser_verify_flash, allow_keep=True, auto_detect=True)
  3167. parser_erase_flash = subparsers.add_parser(
  3168. 'erase_flash',
  3169. help='Perform Chip Erase on SPI flash')
  3170. add_spi_connection_arg(parser_erase_flash)
  3171. parser_erase_region = subparsers.add_parser(
  3172. 'erase_region',
  3173. help='Erase a region of the flash')
  3174. add_spi_connection_arg(parser_erase_region)
  3175. parser_erase_region.add_argument('address', help='Start address (must be multiple of 4096)', type=arg_auto_int)
  3176. parser_erase_region.add_argument('size', help='Size of region to erase (must be multiple of 4096)', type=arg_auto_int)
  3177. parser_merge_bin = subparsers.add_parser(
  3178. 'merge_bin',
  3179. help='Merge multiple raw binary files into a single file for later flashing')
  3180. parser_merge_bin.add_argument('--output', '-o', help='Output filename', type=str, required=True)
  3181. parser_merge_bin.add_argument('--format', '-f', help='Format of the output file', choices='raw', default='raw') # for future expansion
  3182. add_spi_flash_subparsers(parser_merge_bin, allow_keep=True, auto_detect=False)
  3183. parser_merge_bin.add_argument('--target-offset', '-t', help='Target offset where the output file will be flashed',
  3184. type=arg_auto_int, default=0)
  3185. parser_merge_bin.add_argument('--fill-flash-size', help='If set, the final binary file will be padded with FF '
  3186. 'bytes up to this flash size.', action=FlashSizeAction)
  3187. parser_merge_bin.add_argument('addr_filename', metavar='<address> <filename>',
  3188. help='Address followed by binary filename, separated by space',
  3189. action=AddrFilenamePairAction)
  3190. subparsers.add_parser(
  3191. 'version', help='Print esptool version')
  3192. subparsers.add_parser('get_security_info', help='Get some security-related data')
  3193. # internal sanity check - every operation matches a module function of the same name
  3194. for operation in subparsers.choices.keys():
  3195. assert operation in globals(), "%s should be a module function" % operation
  3196. argv = expand_file_arguments(argv or sys.argv[1:])
  3197. args = parser.parse_args(argv)
  3198. print('esptool.py v%s' % __version__)
  3199. # operation function can take 1 arg (args), 2 args (esp, arg)
  3200. # or be a member function of the ESPLoader class.
  3201. if args.operation is None:
  3202. parser.print_help()
  3203. sys.exit(1)
  3204. # Forbid the usage of both --encrypt, which means encrypt all the given files,
  3205. # and --encrypt-files, which represents the list of files to encrypt.
  3206. # The reason is that allowing both at the same time increases the chances of
  3207. # having contradictory lists (e.g. one file not available in one of list).
  3208. if args.operation == "write_flash" and args.encrypt and args.encrypt_files is not None:
  3209. raise FatalError("Options --encrypt and --encrypt-files must not be specified at the same time.")
  3210. operation_func = globals()[args.operation]
  3211. if PYTHON2:
  3212. # This function is depreciated in Python3
  3213. operation_args = inspect.getargspec(operation_func).args
  3214. else:
  3215. operation_args = inspect.getfullargspec(operation_func).args
  3216. if operation_args[0] == 'esp': # operation function takes an ESPLoader connection object
  3217. if args.before != "no_reset_no_sync":
  3218. initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
  3219. else:
  3220. initial_baud = args.baud
  3221. if args.port is None:
  3222. ser_list = get_port_list()
  3223. print("Found %d serial ports" % len(ser_list))
  3224. else:
  3225. ser_list = [args.port]
  3226. esp = esp or get_default_connected_device(ser_list, port=args.port, connect_attempts=args.connect_attempts,
  3227. initial_baud=initial_baud, chip=args.chip, trace=args.trace,
  3228. before=args.before)
  3229. if esp is None:
  3230. raise FatalError("Could not connect to an Espressif device on any of the %d available serial ports." % len(ser_list))
  3231. if esp.secure_download_mode:
  3232. print("Chip is %s in Secure Download Mode" % esp.CHIP_NAME)
  3233. else:
  3234. print("Chip is %s" % (esp.get_chip_description()))
  3235. print("Features: %s" % ", ".join(esp.get_chip_features()))
  3236. print("Crystal is %dMHz" % esp.get_crystal_freq())
  3237. read_mac(esp, args)
  3238. if not args.no_stub:
  3239. if esp.secure_download_mode:
  3240. print("WARNING: Stub loader is not supported in Secure Download Mode, setting --no-stub")
  3241. args.no_stub = True
  3242. else:
  3243. esp = esp.run_stub()
  3244. if args.override_vddsdio:
  3245. esp.override_vddsdio(args.override_vddsdio)
  3246. if args.baud > initial_baud:
  3247. try:
  3248. esp.change_baud(args.baud)
  3249. except NotImplementedInROMError:
  3250. print("WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d" % initial_baud)
  3251. # override common SPI flash parameter stuff if configured to do so
  3252. if hasattr(args, "spi_connection") and args.spi_connection is not None:
  3253. if esp.CHIP_NAME != "ESP32":
  3254. raise FatalError("Chip %s does not support --spi-connection option." % esp.CHIP_NAME)
  3255. print("Configuring SPI flash mode...")
  3256. esp.flash_spi_attach(args.spi_connection)
  3257. elif args.no_stub:
  3258. print("Enabling default SPI flash mode...")
  3259. # ROM loader doesn't enable flash unless we explicitly do it
  3260. esp.flash_spi_attach(0)
  3261. if hasattr(args, "flash_size"):
  3262. print("Configuring flash size...")
  3263. detect_flash_size(esp, args)
  3264. if args.flash_size != 'keep': # TODO: should set this even with 'keep'
  3265. esp.flash_set_parameters(flash_size_bytes(args.flash_size))
  3266. try:
  3267. operation_func(esp, args)
  3268. finally:
  3269. try: # Clean up AddrFilenamePairAction files
  3270. for address, argfile in args.addr_filename:
  3271. argfile.close()
  3272. except AttributeError:
  3273. pass
  3274. # Handle post-operation behaviour (reset or other)
  3275. if operation_func == load_ram:
  3276. # the ESP is now running the loaded image, so let it run
  3277. print('Exiting immediately.')
  3278. elif args.after == 'hard_reset':
  3279. print('Hard resetting via RTS pin...')
  3280. esp.hard_reset()
  3281. elif args.after == 'soft_reset':
  3282. print('Soft resetting...')
  3283. # flash_finish will trigger a soft reset
  3284. esp.soft_reset(False)
  3285. else:
  3286. print('Staying in bootloader.')
  3287. if esp.IS_STUB:
  3288. esp.soft_reset(True) # exit stub back to ROM loader
  3289. if not external_esp:
  3290. esp._port.close()
  3291. else:
  3292. operation_func(args)
  3293. def get_port_list():
  3294. if list_ports is None:
  3295. raise FatalError("Listing all serial ports is currently not available. Please try to specify the port when "
  3296. "running esptool.py or update the pyserial package to the latest version")
  3297. return sorted(ports.device for ports in list_ports.comports())
  3298. def expand_file_arguments(argv):
  3299. """ Any argument starting with "@" gets replaced with all values read from a text file.
  3300. Text file arguments can be split by newline or by space.
  3301. Values are added "as-is", as if they were specified in this order on the command line.
  3302. """
  3303. new_args = []
  3304. expanded = False
  3305. for arg in argv:
  3306. if arg.startswith("@"):
  3307. expanded = True
  3308. with open(arg[1:], "r") as f:
  3309. for line in f.readlines():
  3310. new_args += shlex.split(line)
  3311. else:
  3312. new_args.append(arg)
  3313. if expanded:
  3314. print("esptool.py %s" % (" ".join(new_args[1:])))
  3315. return new_args
  3316. return argv
  3317. class FlashSizeAction(argparse.Action):
  3318. """ Custom flash size parser class to support backwards compatibility with megabit size arguments.
  3319. (At next major relase, remove deprecated sizes and this can become a 'normal' choices= argument again.)
  3320. """
  3321. def __init__(self, option_strings, dest, nargs=1, auto_detect=False, **kwargs):
  3322. super(FlashSizeAction, self).__init__(option_strings, dest, nargs, **kwargs)
  3323. self._auto_detect = auto_detect
  3324. def __call__(self, parser, namespace, values, option_string=None):
  3325. try:
  3326. value = {
  3327. '2m': '256KB',
  3328. '4m': '512KB',
  3329. '8m': '1MB',
  3330. '16m': '2MB',
  3331. '32m': '4MB',
  3332. '16m-c1': '2MB-c1',
  3333. '32m-c1': '4MB-c1',
  3334. }[values[0]]
  3335. print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
  3336. print("Please use the equivalent size '%s'." % (value))
  3337. print("Megabit arguments may be removed in a future release.")
  3338. except KeyError:
  3339. value = values[0]
  3340. known_sizes = dict(ESP8266ROM.FLASH_SIZES)
  3341. known_sizes.update(ESP32ROM.FLASH_SIZES)
  3342. if self._auto_detect:
  3343. known_sizes['detect'] = 'detect'
  3344. known_sizes['keep'] = 'keep'
  3345. if value not in known_sizes:
  3346. raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
  3347. setattr(namespace, self.dest, value)
  3348. class SpiConnectionAction(argparse.Action):
  3349. """ Custom action to parse 'spi connection' override. Values are SPI, HSPI, or a sequence of 5 pin numbers separated by commas.
  3350. """
  3351. def __call__(self, parser, namespace, value, option_string=None):
  3352. if value.upper() == "SPI":
  3353. value = 0
  3354. elif value.upper() == "HSPI":
  3355. value = 1
  3356. elif "," in value:
  3357. values = value.split(",")
  3358. if len(values) != 5:
  3359. raise argparse.ArgumentError(self, '%s is not a valid list of comma-separate pin numbers. Must be 5 numbers - CLK,Q,D,HD,CS.' % value)
  3360. try:
  3361. values = tuple(int(v, 0) for v in values)
  3362. except ValueError:
  3363. raise argparse.ArgumentError(self, '%s is not a valid argument. All pins must be numeric values' % values)
  3364. if any([v for v in values if v > 33 or v < 0]):
  3365. raise argparse.ArgumentError(self, 'Pin numbers must be in the range 0-33.')
  3366. # encode the pin numbers as a 32-bit integer with packed 6-bit values, the same way ESP32 ROM takes them
  3367. # TODO: make this less ESP32 ROM specific somehow...
  3368. clk, q, d, hd, cs = values
  3369. value = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk
  3370. else:
  3371. raise argparse.ArgumentError(self, '%s is not a valid spi-connection value. '
  3372. 'Values are SPI, HSPI, or a sequence of 5 pin numbers CLK,Q,D,HD,CS).' % value)
  3373. setattr(namespace, self.dest, value)
  3374. class AddrFilenamePairAction(argparse.Action):
  3375. """ Custom parser class for the address/filename pairs passed as arguments """
  3376. def __init__(self, option_strings, dest, nargs='+', **kwargs):
  3377. super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
  3378. def __call__(self, parser, namespace, values, option_string=None):
  3379. # validate pair arguments
  3380. pairs = []
  3381. for i in range(0, len(values), 2):
  3382. try:
  3383. address = int(values[i], 0)
  3384. except ValueError:
  3385. raise argparse.ArgumentError(self, 'Address "%s" must be a number' % values[i])
  3386. try:
  3387. argfile = open(values[i + 1], 'rb')
  3388. except IOError as e:
  3389. raise argparse.ArgumentError(self, e)
  3390. except IndexError:
  3391. raise argparse.ArgumentError(self, 'Must be pairs of an address and the binary filename to write there')
  3392. pairs.append((address, argfile))
  3393. # Sort the addresses and check for overlapping
  3394. end = 0
  3395. for address, argfile in sorted(pairs, key=lambda x: x[0]):
  3396. argfile.seek(0, 2) # seek to end
  3397. size = argfile.tell()
  3398. argfile.seek(0)
  3399. sector_start = address & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)
  3400. sector_end = ((address + size + ESPLoader.FLASH_SECTOR_SIZE - 1) & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)) - 1
  3401. if sector_start < end:
  3402. message = 'Detected overlap at address: 0x%x for file: %s' % (address, argfile.name)
  3403. raise argparse.ArgumentError(self, message)
  3404. end = sector_end
  3405. setattr(namespace, self.dest, pairs)
  3406. # Binary stub code (see flasher_stub dir for source & details)
  3407. ESP8266ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3408. eNq9PGtj1Da2f8V2QpIZJkWyPR6bR5lMkikUKJAuge6md+MnvdwCYcg22W7Y3359XpLsmSTQ14fAyJalo3OOzlv6z+ZpfX66edsrNo/O8/ToXKujc6Wm7T/66Lxp4G9+Co/sX9b+pfj2fvsgla5tI1X0Jz3T2G1P\
  3409. p/LrwQ5/kMVmKPg3oyl1eHReQlt5Hswd5u0/0f7ReQ0/4G0OgNXt98kCXj1vWzF8C+Mm8EPLk3YENQYovn3RDqo8mP4n+GbWzjNGsBT11cUuQAg/ud/sBfx7OzEPgl38V75sJ6kLmgS+m7TwhPf99qGAQD9aoGpc\
  3410. 2e2wC8Jz6XG0CUuhhadJF9vyxx8O2n8shD/AMHNAUafTD51O8EnUQlMhrLdb8FUJj0yH8ICnAVII8ltGWAAJ6FWOLcMBqcsBwg71/acPdh4SG+Ulv81j09hql6tg4BbLuu3T5NxAcHDoY+G57tr1CnwA9lc9S8su\
  3411. D9IMvY52kt5LXgjhzzTa+TedEeNV4DLIncWr1Bmk6L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7dU+D0pi/vWgfZXLKXOL6UJN70bxGwEJIJZyJV0a37hvgEK1VKJwbg5r7N+Q0FxU50g0Sj5EzdeIMP\
  3470. ZmAat3DuTaoKvJQCp4Cvy2BgszvkHhuDCC9lHdvzDZrmw/ssrEiXgfHwayiwF51PrBFmPruQS+yazjnXNaxpCp8Bo+GB+wjOhRTjwbM9Sz4d2yNlgooJHkhUzDW6CMxZDKXBUC/2Dvn8Yz1hPQmdHABSqhbBJ5PE\
  3471. iWeEqww1+tt7eGivLuRe7SK2AP7QhR9iH5ctgYIhFMxrgZ0xnM0h16c1bgeZpcRi0isB6YOLc4Kr1g5/6skRKU66LX0Tuti1rzdHHt6Y/M+Pp/kC7k3WahKn8WQSx+2b+t3p4t/uw7R9WOWnOV+w3LkPFnff2LG6\
  3472. pXhXIpRyYJ8L2zLe2nihbVk4DTDyTANvAMGLnKc7XKqAfWrz+G8U8sDHuTIN27sg8YodqtppYO+i19v+SimS05sZol51I8NVTgPDy+rS4YhxljpwShetiek9Pm6uphdk3re/7vB9znK1cDO+dIpVv26Te9N5psyv\
  3473. 93zdkZr+n0Hof80clFK0yCtXYJf5OxEIi8+E68t/2SxS27jvwIXFTgLx0j26/RxD1Gv3vcTeiU5bN4t/3cvDF7092ZvbvVAJTbVOELBj1HSstP4Vzp2AhF5xcbTu9de992GvHfXaca+d9Nppr11227oHj+7099xG\
  3474. p6d7W7U+vvr+4z/0T1/TDr+Qh67jqet4rN9OrmlPrmmnV7ZPr2i9u6LVucl6Zbu8sr24au9c+/el+zb5IhydfsG6+5A310iBHuS6B0n/GnPdGW/Nbdx0G51h77iNXbfRsSw6BPnYkzQ9OPNeu+y162jFLtF/4S7+\
  3475. s6XA75USv1eK/F4p83ul0HXtL/zTygYmzQ6c4M6jSiRxNWJzzTffeicxPLPTVum4S1e6yVara+RGk1DFafrp/wG5amLt\
  3476. """)))
  3477. ESP32ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3478. eNqNWntz3LYR/yoUrX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OROKbwOKZKSQLIZ38hl1FZ3w7PHtwuZ2DfC7h5BLZgnZO/N+HLDFSRNBu5tKtwzx3j1teHYdHbeFfzxOvItXEfm53gdme/nE+BZnXFMWQo+kajYX3fSehBdeoC4gLZ2g23O5ULLYJrJbS6G983W\
  3505. rxwE0CX8fUkm3WBNRWE9K9vfFTQBHjE1xGT6hXdrJVtGg26teePvZa3e+olzkIImgpaCJpb6H1yN5XsaKyUDS3EStg1dg1Ep6ud1IVoMAiqzC9t98I6zZIW0eOMNXyV9qMiBlnDbbLgQCyMBTkDIlDZEdIHOr1gK\
  3506. jPyKWDAsySfhrZ6IuKH0s2z4blR+HRHcKorMKATY+YnVkOm2KJ0D/DmS/hIOZ98QxIMOYlDaam5wxFpnB1xDB62Dq5Oa9YXqawdsP6hl+dn1PPg9iH1JqEWY/ETy1WwwRTvdhrmioebge0BxAQKjt8KvxcH1/N/y\
  3507. dT++SggDyy7oOt6AXOCUEfH1X9e/Gj0dds5vux1AxaEAAL/p8Ju8/DN4zNYHYLurkbCS9W/Qut+ZiS52WQJX6uinIHTzbTFw4vt8DAdzHxcptLTRE3kdHyzu0nCV78Z0AmaQzq7dJKuDZ7IvWmgsC7dQ9KE94+5G\
  3508. es//WItIw9HP+V5n0211LT8iE9ay3tTYk9KX1d5RhD9m/OnjsryHnzRqlafjxAkxdV+a2+X9p65Tp0XmOutyWQa/feSa/x5/CRcaZWo8TtPP/wO9arcm\
  3509. """)))
  3510. ESP32S2ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3511. eNqNW3t31LYS/yobQ5INgVvJ67Vl2p5soN0ToA+S0jTl5JzGku2EHm5usg2wodDPfjUvS951uPcPE68sjUajefxmJP7evmmWN9uPR3b7dKmMfxQ8Z6dL7aIf9MI/Krd7umybPd8nNOf78GfDf6j8054unRpBC5BM\
  3512. /be27DWP/T/ZyL+WmX/8VE3qW3L/TOPZYOCUBhrt/+Y9Ip4VIO8pGEPcV9Cmbjw5FS3HJi1w4VsL3x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
  3545. R8Jd6sIFRyOZD3hDl4ZLLKarGHa3NWDEJyoi49eG81+NGcZWEvzcFy+uqZ17Mi9eikqEcIvpQBHtS40lB7m9RKxh70d8JhzN1c1RyzV3WVreG5oEVvqy2n44wv9Z8cdfN9UC/n+FVsWkVNM8z/yX5vJmcds1FlOd\
  3546. +8a6uqlW/iNGW+9t85ceoTxNlco+/xcolYoO\
  3547. """)))
  3548. ESP32S3BETA2ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3549. eNqNWntz2zYS/yqKYtmRm84QfIKezkVSHVlOrlc7TRQnVadHguT1pjmP7Ki17HO++2FfBEip7f1BmwTBxWIfv31A/z3a1NvN0cmgPFptA22vAK5/rrbKeA90ww9F/NVqa8oXdo4bTqfw78lq2xT2auyEYAAjQDK0\
  3550. 75q8M/zM/okH9jaP7WWXqkM7ktor8VeDDxP6UCv7P+0QsawAeUtBa+K+gLFgY8kF3nbKYQNc2NHMTgUaMdABZlWHYE7TVGVHWx7e4qt/vvX3aXmGL6seO5YNu7aGu+BguaC3OLP4f2Z214Xr+aBVwGBHFbBDYacG\
  3551. KRnZVUn0AkNCcKvyBpGl0pNr3mMvD3+hGzeCEl7e7+7DUny0oyFsZRiATkEju3uBa0L81sKsnWfVkReOlbrypGb6bOW9DXW52r8mX8rd68D7OmBbBgJy4cR40DNs5CYc8v7Sb8FYYSfa7aQu6G2RiID1jPQAs+C/\
  3552. ii/F/jK231IPgaeI/MmY6JLEiUSNGPhwYucqNbLjkae5gO9hW0jBG+zqPbJvqrDz5o3paPkKZi1/I7YnEYznMz189e35sCvcPPAEBwqB5U3xQizaE3XsP08mcrcA4vwNQABTE3Mulch1wA4NEi15Yi6STrqwkHv3\
  3553. LRLkrGjtW3MZjj03ZnnmbM+dmTnggXbbhgvUp6x2Tc674LH2IxNe8ReWy7z0ASs87zuWtwA6QOG4kcVEqnifgR/MeXLsdl4zUBZwzzaJ6/sOYxB3Su9TpAeGCTQBHILgkQjAG2UJ1GoOH/ne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ESP32S3BETA3ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3582. eNqNWntz2zYS/yqKYtmWm84QfDPTuUiqI9tJe7XTRHFy7rQgSLY37XlkR61ln/PdD/siQIpt7w9KJAgsFovd3z7A/x5s6u3m4PmoPLjaBrm9Arh+utoq4z3QDT/o+IurrSlf2D6uOZ3D35OrbaPt1dgOwQhagGRo\
  3583. 3zVFp/nQ/sQje1vE9rJT1aFtSe2V+LPBwIQG5sr+px0ilhUgbynkOXGvoS3YWHKBt5xy3AAXtjWzXYFGDHSAWdUhWFA3VdnWloe3+Oqnt/46Lc8wsuqxY9mwc+dwF+ytTukt9tT/T8/uvHA9G7UbMNrZClihsFOD\
  3584. lIysqiR6gSEhuFl5gchS6cm16LFXhL/QjWtBCa/ud9dhKT7a1hCWMg5gT2FHdtcC14z4rYVZ289uR6EdK3XlSc302Sp6C+pyNTwnX8rd54E3OmBdBgJyYcd41FNs5CYc8/rSr0FZYSW5W0mt6a1ORMD5gvYBesG/\
  3585. ii9E/zLW3zIfA08R2ZMx0QWJE4kaUfDxzPZVamLbI2/nAr6HZSEFr7G775F9U4WdN29MZ5cvodfqd2J7FkF7scjHr74+G3eFWwSe4GBDYHqjX4hGe6KO/efZTO5OgTiPAQhgaqLOpRK5jtigQaIldyxE0kkXFgrv\
  3586. vkWCgjc697W5DKeeGbM8C9bnTs8C8CB3y4YLtk/Z3TUFr4Lb2kEmvOQRlsui9AErPOsbljcBGoB23MhkIlW8z8AOltw5diuvGSg13LNO4vy+wRjEndIbivRAMYEmgEMQPBIBeKMsgVotYZBvTb5mXftyLa42LZlu\
  3587. +3V31IaYrjxGczKRTUc4LMi+aVc5scSAYn9K3MXL+DwybIsRqPMlmNzH78+vruaE/UTBmlHN6JLnx1ZoKe8C2toeLR6tOKR/EZePV2C9KoZ1RgB7ZThifWQr851Qbp6PSStNPH17CAOfj6fwdxiDuKypdVBzTS6x\
  3588. 0WhhXfBHK/oFJGrvN/yfatYwy2yFIOoBu0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1K38Y3KC/ThH5AKrpr+kGWiofA/CMJjjmY0wwGCgXgrwVlwvxoxk5sMq9\
  3608. +r3sq04u+aCLQdjyfcDnFqlYPgLyAYGwZj9XJ+cD55w0GARiYhFIQgECLmpgM1X6qneyBWZevOeTw+wVl3QLWlWeZzP8JuAMHtRDn+CSI/+ajW1XzkxYrfFQceFxGHIOL6gO6pCOduuGhUJFvwG3Wl3i9znFzTmG\
  3609. 6/d6uy94dOdOKAPznJaAeZnIHv3j5MKdERt18y/iXfNpqVYfuQDMB0QIZHzcjMWHnCpXGItLG3hmteP0fwAgLPN9mOuGpFApb+dZnw0ew+/LsSs3kCfWcAKecy0YOgdc5UYfnYzoYJ8fQeeTtSMKFgWaAnktHjGK\
  3610. nGtyeLrmU1r5akMORbIB2SU/dPWWVnNPnwscwsZsC3IXOj+Hmoc6d3FvlU65jG8yOr2B2pzGesPFUzYz1MXs7N3S+0gFVKVoM597krCC6kjBGIhib4fnZ5fLPxyOwEkx6k7boTj7sPwkHU4nqw3Rd2eG8wH4U18I\
  3611. 5g5EU7n6x45N/NrOkHARDvbBTVL8Hcaq3Q54L0WFlBG4W+tvP4GTidp045AP7DOOiqAkaEL3UQFCVeYCrAA/w4keyW+5qHOfugfZ/phBsJcU7xxrB9OnMi8a6lgIN1A6ojnH7fH4gfuUjFjD3l/y6dLQ0Xkln7jJ\
  3612. 0tLO0LFjpSurg2cj/MLyx08bfQvfWaogy6KsCLLQvqmvN7f30pgHiUptY6U3uvdBptEvDviNTygIsyIpws//Ay4v6A0=\
  3613. """)))
  3614. ESP32C3ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  3615. eNrFWmt328YR/SuypEix29PugngqtUw6lChKlmvnpFGcA6UGdgHVSatTyVQtt+V/7955ECAl0vnWD3wBi93ZmTt3Hsv/7M+a+9n+wVa9X94bW97b8Kqz8B0v8/60vHd5+DYo76uivM/p6l64WL0Ob+l34S0Ol9Lw\
  3616. 2WyHNydPx/R0ed/6dxnN8SK8mVd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xEC6Fl3ht3/I4Ul9VxIV9cSmO8Yyfq/EUW2/p2DheEsYCBHjlnXX3tcsafdfnJzuDZlOJb+dfx4Kq/2Llo2Jnl23F2v5Pwht/rXhn/piaUiKGWv2dClYp/M20Nuvi2wR2ETf3gKE15zk4776SF31E5/3K1gkhM5\
  3643. MW8577o9eYmW3YH060jkP1KdOolO5D8YDKSA1VJaEZKnahPF6msgxIyItk7rjP/ogna/L4kFsOOGYk3kMZTaedkw9WGjC8QOCvZUD+mBQiInsKb3DwKRiw4PPM729SiZ/k1BHFNw/GlS6XYvOW2x0/U0yDMSDg6S\
  3644. Rsy4sdmIbrFkFXXLS6TpOygsr8UtLe/kMaNNrcc57PlDn3t85LDY5Hh/YoeoK0nMiPZyCVbNRhEg48FvchMQhZZpMR/WEabTN3toWKcoXVK0rNNpi5Z1enoM90/P9lAnp69wG5VFdNksmtb7v9+ivyf+9eOsusWf\
  3645. FK3JstjaPDbhTnM9u/28uDgYRLjoq1ml/2YEpIIv7cvl/izGpnFh4vn/AOixonk=\
  3646. """)))
  3647. def _main():
  3648. try:
  3649. main()
  3650. except FatalError as e:
  3651. print('\nA fatal error occurred: %s' % e)
  3652. sys.exit(2)
  3653. if __name__ == '__main__':
  3654. _main()