esptool.py 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959
  1. #!/usr/bin/env python
  2. #
  3. # ESP8266 & ESP32 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 os
  27. import shlex
  28. import struct
  29. import sys
  30. import time
  31. import zlib
  32. import string
  33. try:
  34. import serial
  35. except ImportError:
  36. print("Pyserial is not installed for %s. Check the README for installation instructions." % (sys.executable))
  37. raise
  38. # check 'serial' is 'pyserial' and not 'serial' https://github.com/espressif/esptool/issues/269
  39. try:
  40. if "serialization" in serial.__doc__ and "deserialization" in serial.__doc__:
  41. raise ImportError("""
  42. esptool.py depends on pyserial, but there is a conflict with a currently installed package named 'serial'.
  43. You may be able to work around this by 'pip uninstall serial; pip install pyserial' \
  44. but this may break other installed Python software that depends on 'serial'.
  45. There is no good fix for this right now, apart from configuring virtualenvs. \
  46. See https://github.com/espressif/esptool/issues/269#issuecomment-385298196 for discussion of the underlying issue(s).""")
  47. except TypeError:
  48. pass # __doc__ returns None for pyserial
  49. try:
  50. import serial.tools.list_ports as list_ports
  51. except ImportError:
  52. print("The installed version (%s) of pyserial appears to be too old for esptool.py (Python interpreter %s). "
  53. "Check the README for installation instructions." % (sys.VERSION, sys.executable))
  54. raise
  55. __version__ = "2.6"
  56. MAX_UINT32 = 0xffffffff
  57. MAX_UINT24 = 0xffffff
  58. DEFAULT_TIMEOUT = 3 # timeout for most flash operations
  59. START_FLASH_TIMEOUT = 20 # timeout for starting flash (may perform erase)
  60. CHIP_ERASE_TIMEOUT = 120 # timeout for full chip erase
  61. MAX_TIMEOUT = CHIP_ERASE_TIMEOUT * 2 # longest any command can run
  62. SYNC_TIMEOUT = 0.1 # timeout for syncing with bootloader
  63. MD5_TIMEOUT_PER_MB = 8 # timeout (per megabyte) for calculating md5sum
  64. ERASE_REGION_TIMEOUT_PER_MB = 30 # timeout (per megabyte) for erasing a region
  65. MEM_END_ROM_TIMEOUT = 0.05 # special short timeout for ESP_MEM_END, as it may never respond
  66. DEFAULT_SERIAL_WRITE_TIMEOUT = 10 # timeout for serial port write
  67. def timeout_per_mb(seconds_per_mb, size_bytes):
  68. """ Scales timeouts which are size-specific """
  69. result = seconds_per_mb * (size_bytes / 1e6)
  70. if result < DEFAULT_TIMEOUT:
  71. return DEFAULT_TIMEOUT
  72. return result
  73. DETECTED_FLASH_SIZES = {0x12: '256KB', 0x13: '512KB', 0x14: '1MB',
  74. 0x15: '2MB', 0x16: '4MB', 0x17: '8MB', 0x18: '16MB'}
  75. def check_supported_function(func, check_func):
  76. """
  77. Decorator implementation that wraps a check around an ESPLoader
  78. bootloader function to check if it's supported.
  79. This is used to capture the multidimensional differences in
  80. functionality between the ESP8266 & ESP32 ROM loaders, and the
  81. software stub that runs on both. Not possible to do this cleanly
  82. via inheritance alone.
  83. """
  84. def inner(*args, **kwargs):
  85. obj = args[0]
  86. if check_func(obj):
  87. return func(*args, **kwargs)
  88. else:
  89. raise NotImplementedInROMError(obj, func)
  90. return inner
  91. def stub_function_only(func):
  92. """ Attribute for a function only supported in the software stub loader """
  93. return check_supported_function(func, lambda o: o.IS_STUB)
  94. def stub_and_esp32_function_only(func):
  95. """ Attribute for a function only supported by software stubs or ESP32 ROM """
  96. return check_supported_function(func, lambda o: o.IS_STUB or o.CHIP_NAME == "ESP32")
  97. PYTHON2 = sys.version_info[0] < 3 # True if on pre-Python 3
  98. # Function to return nth byte of a bitstring
  99. # Different behaviour on Python 2 vs 3
  100. if PYTHON2:
  101. def byte(bitstr, index):
  102. return ord(bitstr[index])
  103. else:
  104. def byte(bitstr, index):
  105. return bitstr[index]
  106. # Provide a 'basestring' class on Python 3
  107. try:
  108. basestring
  109. except NameError:
  110. basestring = str
  111. def esp8266_function_only(func):
  112. """ Attribute for a function only supported on ESP8266 """
  113. return check_supported_function(func, lambda o: o.CHIP_NAME == "ESP8266")
  114. class ESPLoader(object):
  115. """ Base class providing access to ESP ROM & software stub bootloaders.
  116. Subclasses provide ESP8266 & ESP32 specific functionality.
  117. Don't instantiate this base class directly, either instantiate a subclass or
  118. call ESPLoader.detect_chip() which will interrogate the chip and return the
  119. appropriate subclass instance.
  120. """
  121. CHIP_NAME = "Espressif device"
  122. IS_STUB = False
  123. DEFAULT_PORT = "/dev/ttyUSB0"
  124. # Commands supported by ESP8266 ROM bootloader
  125. ESP_FLASH_BEGIN = 0x02
  126. ESP_FLASH_DATA = 0x03
  127. ESP_FLASH_END = 0x04
  128. ESP_MEM_BEGIN = 0x05
  129. ESP_MEM_END = 0x06
  130. ESP_MEM_DATA = 0x07
  131. ESP_SYNC = 0x08
  132. ESP_WRITE_REG = 0x09
  133. ESP_READ_REG = 0x0a
  134. # Some comands supported by ESP32 ROM bootloader (or -8266 w/ stub)
  135. ESP_SPI_SET_PARAMS = 0x0B
  136. ESP_SPI_ATTACH = 0x0D
  137. ESP_CHANGE_BAUDRATE = 0x0F
  138. ESP_FLASH_DEFL_BEGIN = 0x10
  139. ESP_FLASH_DEFL_DATA = 0x11
  140. ESP_FLASH_DEFL_END = 0x12
  141. ESP_SPI_FLASH_MD5 = 0x13
  142. # Some commands supported by stub only
  143. ESP_ERASE_FLASH = 0xD0
  144. ESP_ERASE_REGION = 0xD1
  145. ESP_READ_FLASH = 0xD2
  146. ESP_RUN_USER_CODE = 0xD3
  147. # Maximum block sized for RAM and Flash writes, respectively.
  148. ESP_RAM_BLOCK = 0x1800
  149. FLASH_WRITE_SIZE = 0x400
  150. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  151. ESP_ROM_BAUD = 115200
  152. # First byte of the application image
  153. ESP_IMAGE_MAGIC = 0xe9
  154. # Initial state for the checksum routine
  155. ESP_CHECKSUM_MAGIC = 0xef
  156. # Flash sector size, minimum unit of erase.
  157. FLASH_SECTOR_SIZE = 0x1000
  158. UART_DATA_REG_ADDR = 0x60000078
  159. # Memory addresses
  160. IROM_MAP_START = 0x40200000
  161. IROM_MAP_END = 0x40300000
  162. # The number of bytes in the UART response that signify command status
  163. STATUS_BYTES_LENGTH = 2
  164. def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
  165. """Base constructor for ESPLoader bootloader interaction
  166. Don't call this constructor, either instantiate ESP8266ROM
  167. or ESP32ROM, or use ESPLoader.detect_chip().
  168. This base class has all of the instance methods for bootloader
  169. functionality supported across various chips & stub
  170. loaders. Subclasses replace the functions they don't support
  171. with ones which throw NotImplementedInROMError().
  172. """
  173. if isinstance(port, basestring):
  174. self._port = serial.serial_for_url(port)
  175. else:
  176. self._port = port
  177. self._slip_reader = slip_reader(self._port, self.trace)
  178. # setting baud rate in a separate step is a workaround for
  179. # CH341 driver on some Linux versions (this opens at 9600 then
  180. # sets), shouldn't matter for other platforms/drivers. See
  181. # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
  182. self._set_port_baudrate(baud)
  183. self._trace_enabled = trace_enabled
  184. # set write timeout, to prevent esptool blocked at write forever.
  185. try:
  186. self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT
  187. except NotImplementedError:
  188. # no write timeout for RFC2217 ports
  189. # need to set the property back to None or it will continue to fail
  190. self._port.write_timeout = None
  191. def _set_port_baudrate(self, baud):
  192. try:
  193. self._port.baudrate = baud
  194. except IOError:
  195. raise FatalError("Failed to set baud rate %d. The driver may not support this rate." % baud)
  196. @staticmethod
  197. def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False):
  198. """ Use serial access to detect the chip type.
  199. We use the UART's datecode register for this, it's mapped at
  200. the same address on ESP8266 & ESP32 so we can use one
  201. memory read and compare to the datecode register for each chip
  202. type.
  203. This routine automatically performs ESPLoader.connect() (passing
  204. connect_mode parameter) as part of querying the chip.
  205. """
  206. detect_port = ESPLoader(port, baud, trace_enabled=trace_enabled)
  207. detect_port.connect(connect_mode)
  208. try:
  209. print('Detecting chip type...', end='')
  210. sys.stdout.flush()
  211. date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR)
  212. for cls in [ESP8266ROM, ESP32ROM]:
  213. if date_reg == cls.DATE_REG_VALUE:
  214. # don't connect a second time
  215. inst = cls(detect_port._port, baud, trace_enabled=trace_enabled)
  216. print(' %s' % inst.CHIP_NAME, end='')
  217. return inst
  218. finally:
  219. print('') # end line
  220. raise FatalError("Unexpected UART datecode value 0x%08x. Failed to autodetect chip type." % date_reg)
  221. """ Read a SLIP packet from the serial port """
  222. def read(self):
  223. return next(self._slip_reader)
  224. """ Write bytes to the serial port while performing SLIP escaping """
  225. def write(self, packet):
  226. buf = b'\xc0' \
  227. + (packet.replace(b'\xdb',b'\xdb\xdd').replace(b'\xc0',b'\xdb\xdc')) \
  228. + b'\xc0'
  229. self.trace("Write %d bytes: %s", len(buf), HexFormatter(buf))
  230. self._port.write(buf)
  231. def trace(self, message, *format_args):
  232. if self._trace_enabled:
  233. now = time.time()
  234. try:
  235. delta = now - self._last_trace
  236. except AttributeError:
  237. delta = 0.0
  238. self._last_trace = now
  239. prefix = "TRACE +%.3f " % delta
  240. print(prefix + (message % format_args))
  241. """ Calculate checksum of a blob, as it is defined by the ROM """
  242. @staticmethod
  243. def checksum(data, state=ESP_CHECKSUM_MAGIC):
  244. for b in data:
  245. if type(b) is int: # python 2/3 compat
  246. state ^= b
  247. else:
  248. state ^= ord(b)
  249. return state
  250. """ Send a request and read the response """
  251. def command(self, op=None, data=b"", chk=0, wait_response=True, timeout=DEFAULT_TIMEOUT):
  252. saved_timeout = self._port.timeout
  253. new_timeout = min(timeout, MAX_TIMEOUT)
  254. if new_timeout != saved_timeout:
  255. self._port.timeout = new_timeout
  256. try:
  257. if op is not None:
  258. self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%s",
  259. op, len(data), 1 if wait_response else 0, timeout, HexFormatter(data))
  260. pkt = struct.pack(b'<BBHI', 0x00, op, len(data), chk) + data
  261. self.write(pkt)
  262. if not wait_response:
  263. return
  264. # tries to get a response until that response has the
  265. # same operation as the request or a retries limit has
  266. # exceeded. This is needed for some esp8266s that
  267. # reply with more sync responses than expected.
  268. for retry in range(100):
  269. p = self.read()
  270. if len(p) < 8:
  271. continue
  272. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
  273. if resp != 1:
  274. continue
  275. data = p[8:]
  276. if op is None or op_ret == op:
  277. return val, data
  278. finally:
  279. if new_timeout != saved_timeout:
  280. self._port.timeout = saved_timeout
  281. raise FatalError("Response doesn't match request")
  282. def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):
  283. """
  284. Execute a command with 'command', check the result code and throw an appropriate
  285. FatalError if it fails.
  286. Returns the "result" of a successful command.
  287. """
  288. val, data = self.command(op, data, chk, timeout=timeout)
  289. # things are a bit weird here, bear with us
  290. # the status bytes are the last 2/4 bytes in the data (depending on chip)
  291. if len(data) < self.STATUS_BYTES_LENGTH:
  292. raise FatalError("Failed to %s. Only got %d byte status response." % (op_description, len(data)))
  293. status_bytes = data[-self.STATUS_BYTES_LENGTH:]
  294. # we only care if the first one is non-zero. If it is, the second byte is a reason.
  295. if byte(status_bytes, 0) != 0:
  296. raise FatalError.WithResult('Failed to %s' % op_description, status_bytes)
  297. # if we had more data than just the status bytes, return it as the result
  298. # (this is used by the md5sum command, maybe other commands?)
  299. if len(data) > self.STATUS_BYTES_LENGTH:
  300. return data[:-self.STATUS_BYTES_LENGTH]
  301. else: # otherwise, just return the 'val' field which comes from the reply header (this is used by read_reg)
  302. return val
  303. def flush_input(self):
  304. self._port.flushInput()
  305. self._slip_reader = slip_reader(self._port, self.trace)
  306. def sync(self):
  307. self.command(self.ESP_SYNC, b'\x07\x07\x12\x20' + 32 * b'\x55',
  308. timeout=SYNC_TIMEOUT)
  309. for i in range(7):
  310. self.command()
  311. def _setDTR(self, state):
  312. self._port.setDTR(state)
  313. def _setRTS(self, state):
  314. self._port.setRTS(state)
  315. # Work-around for adapters on Windows using the usbser.sys driver:
  316. # generate a dummy change to DTR so that the set-control-line-state
  317. # request is sent with the updated RTS state and the same DTR state
  318. self._port.setDTR(self._port.dtr)
  319. def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
  320. """ A single connection attempt, with esp32r0 workaround options """
  321. # esp32r0_delay is a workaround for bugs with the most common auto reset
  322. # circuit and Windows, if the EN pin on the dev board does not have
  323. # enough capacitance.
  324. #
  325. # Newer dev boards shouldn't have this problem (higher value capacitor
  326. # on the EN pin), and ESP32 revision 1 can't use this workaround as it
  327. # relies on a silicon bug.
  328. #
  329. # Details: https://github.com/espressif/esptool/issues/136
  330. last_error = None
  331. # If we're doing no_sync, we're likely communicating as a pass through
  332. # with an intermediate device to the ESP32
  333. if mode == "no_reset_no_sync":
  334. return last_error
  335. # issue reset-to-bootloader:
  336. # RTS = either CH_PD/EN or nRESET (both active low = chip in reset
  337. # DTR = GPIO0 (active low = boot to flasher)
  338. #
  339. # DTR & RTS are active low signals,
  340. # ie True = pin @ 0V, False = pin @ VCC.
  341. if mode != 'no_reset':
  342. self._setDTR(False) # IO0=HIGH
  343. self._setRTS(True) # EN=LOW, chip in reset
  344. time.sleep(0.1)
  345. if esp32r0_delay:
  346. # Some chips are more likely to trigger the esp32r0
  347. # watchdog reset silicon bug if they're held with EN=LOW
  348. # for a longer period
  349. time.sleep(1.2)
  350. self._setDTR(True) # IO0=LOW
  351. self._setRTS(False) # EN=HIGH, chip out of reset
  352. if esp32r0_delay:
  353. # Sleep longer after reset.
  354. # This workaround only works on revision 0 ESP32 chips,
  355. # it exploits a silicon bug spurious watchdog reset.
  356. time.sleep(0.4) # allow watchdog reset to occur
  357. time.sleep(0.05)
  358. self._setDTR(False) # IO0=HIGH, done
  359. for _ in range(5):
  360. try:
  361. self.flush_input()
  362. self._port.flushOutput()
  363. self.sync()
  364. return None
  365. except FatalError as e:
  366. if esp32r0_delay:
  367. print('_', end='')
  368. else:
  369. print('.', end='')
  370. sys.stdout.flush()
  371. time.sleep(0.05)
  372. last_error = e
  373. return last_error
  374. def connect(self, mode='default_reset'):
  375. """ Try connecting repeatedly until successful, or giving up """
  376. print('Connecting...', end='')
  377. sys.stdout.flush()
  378. last_error = None
  379. try:
  380. for _ in range(7):
  381. last_error = self._connect_attempt(mode=mode, esp32r0_delay=False)
  382. if last_error is None:
  383. return
  384. last_error = self._connect_attempt(mode=mode, esp32r0_delay=True)
  385. if last_error is None:
  386. return
  387. finally:
  388. print('') # end 'Connecting...' line
  389. raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
  390. """ Read memory address in target """
  391. def read_reg(self, addr):
  392. # we don't call check_command here because read_reg() function is called
  393. # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
  394. # for different chip types (!)
  395. val, data = self.command(self.ESP_READ_REG, struct.pack('<I', addr))
  396. if byte(data, 0) != 0:
  397. raise FatalError.WithResult("Failed to read register address %08x" % addr, data)
  398. return val
  399. """ Write to memory address in target """
  400. def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0):
  401. return self.check_command("write target memory", self.ESP_WRITE_REG,
  402. struct.pack('<IIII', addr, value, mask, delay_us))
  403. """ Start downloading an application image to RAM """
  404. def mem_begin(self, size, blocks, blocksize, offset):
  405. if self.IS_STUB: # check we're not going to overwrite a running stub with this data
  406. stub = self.STUB_CODE
  407. load_start = offset
  408. load_end = offset + size
  409. for (start, end) in [(stub["data_start"], stub["data_start"] + len(stub["data"])),
  410. (stub["text_start"], stub["text_start"] + len(stub["text"]))]:
  411. if load_start < end and load_end > start:
  412. raise FatalError(("Software loader is resident at 0x%08x-0x%08x. " +
  413. "Can't load binary at overlapping address range 0x%08x-0x%08x. " +
  414. "Either change binary loading address, or use the --no-stub " +
  415. "option to disable the software loader.") % (start, end, load_start, load_end))
  416. return self.check_command("enter RAM download mode", self.ESP_MEM_BEGIN,
  417. struct.pack('<IIII', size, blocks, blocksize, offset))
  418. """ Send a block of an image to RAM """
  419. def mem_block(self, data, seq):
  420. return self.check_command("write to target RAM", self.ESP_MEM_DATA,
  421. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  422. self.checksum(data))
  423. """ Leave download mode and run the application """
  424. def mem_finish(self, entrypoint=0):
  425. # Sending ESP_MEM_END usually sends a correct response back, however sometimes
  426. # (with ROM loader) the executed code may reset the UART or change the baud rate
  427. # before the transmit FIFO is empty. So in these cases we set a short timeout and
  428. # ignore errors.
  429. timeout = DEFAULT_TIMEOUT if self.IS_STUB else MEM_END_ROM_TIMEOUT
  430. data = struct.pack('<II', int(entrypoint == 0), entrypoint)
  431. try:
  432. return self.check_command("leave RAM download mode", self.ESP_MEM_END,
  433. data=data, timeout=timeout)
  434. except FatalError:
  435. if self.IS_STUB:
  436. raise
  437. pass
  438. """ Start downloading to Flash (performs an erase)
  439. Returns number of blocks (of size self.FLASH_WRITE_SIZE) to write.
  440. """
  441. def flash_begin(self, size, offset):
  442. num_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  443. erase_size = self.get_erase_size(offset, size)
  444. t = time.time()
  445. if self.IS_STUB:
  446. timeout = DEFAULT_TIMEOUT
  447. else:
  448. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, size) # ROM performs the erase up front
  449. self.check_command("enter Flash download mode", self.ESP_FLASH_BEGIN,
  450. struct.pack('<IIII', erase_size, num_blocks, self.FLASH_WRITE_SIZE, offset),
  451. timeout=timeout)
  452. if size != 0 and not self.IS_STUB:
  453. print("Took %.2fs to erase flash block" % (time.time() - t))
  454. return num_blocks
  455. """ Write block to flash """
  456. def flash_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
  457. self.check_command("write to target Flash after seq %d" % seq,
  458. self.ESP_FLASH_DATA,
  459. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  460. self.checksum(data),
  461. timeout=timeout)
  462. """ Leave flash mode and run/reboot """
  463. def flash_finish(self, reboot=False):
  464. pkt = struct.pack('<I', int(not reboot))
  465. # stub sends a reply to this command
  466. self.check_command("leave Flash mode", self.ESP_FLASH_END, pkt)
  467. """ Run application code in flash """
  468. def run(self, reboot=False):
  469. # Fake flash begin immediately followed by flash end
  470. self.flash_begin(0, 0)
  471. self.flash_finish(reboot)
  472. """ Read SPI flash manufacturer and device id """
  473. def flash_id(self):
  474. SPIFLASH_RDID = 0x9F
  475. return self.run_spiflash_command(SPIFLASH_RDID, b"", 24)
  476. def parse_flash_size_arg(self, arg):
  477. try:
  478. return self.FLASH_SIZES[arg]
  479. except KeyError:
  480. raise FatalError("Flash size '%s' is not supported by this chip type. Supported sizes: %s"
  481. % (arg, ", ".join(self.FLASH_SIZES.keys())))
  482. def run_stub(self, stub=None):
  483. if stub is None:
  484. if self.IS_STUB:
  485. raise FatalError("Not possible for a stub to load another stub (memory likely to overlap.)")
  486. stub = self.STUB_CODE
  487. # Upload
  488. print("Uploading stub...")
  489. for field in ['text', 'data']:
  490. if field in stub:
  491. offs = stub[field + "_start"]
  492. length = len(stub[field])
  493. blocks = (length + self.ESP_RAM_BLOCK - 1) // self.ESP_RAM_BLOCK
  494. self.mem_begin(length, blocks, self.ESP_RAM_BLOCK, offs)
  495. for seq in range(blocks):
  496. from_offs = seq * self.ESP_RAM_BLOCK
  497. to_offs = from_offs + self.ESP_RAM_BLOCK
  498. self.mem_block(stub[field][from_offs:to_offs], seq)
  499. print("Running stub...")
  500. self.mem_finish(stub['entry'])
  501. p = self.read()
  502. if p != b'OHAI':
  503. raise FatalError("Failed to start stub. Unexpected response: %s" % p)
  504. print("Stub running...")
  505. return self.STUB_CLASS(self)
  506. @stub_and_esp32_function_only
  507. def flash_defl_begin(self, size, compsize, offset):
  508. """ Start downloading compressed data to Flash (performs an erase)
  509. Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
  510. """
  511. num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  512. erase_blocks = (size + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
  513. t = time.time()
  514. if self.IS_STUB:
  515. write_size = size # stub expects number of bytes here, manages erasing internally
  516. timeout = DEFAULT_TIMEOUT
  517. else:
  518. write_size = erase_blocks * self.FLASH_WRITE_SIZE # ROM expects rounded up to erase block size
  519. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, write_size) # ROM performs the erase up front
  520. print("Compressed %d bytes to %d..." % (size, compsize))
  521. self.check_command("enter compressed flash mode", self.ESP_FLASH_DEFL_BEGIN,
  522. struct.pack('<IIII', write_size, num_blocks, self.FLASH_WRITE_SIZE, offset),
  523. timeout=timeout)
  524. if size != 0 and not self.IS_STUB:
  525. # (stub erases as it writes, but ROM loaders erase on begin)
  526. print("Took %.2fs to erase flash block" % (time.time() - t))
  527. return num_blocks
  528. """ Write block to flash, send compressed """
  529. @stub_and_esp32_function_only
  530. def flash_defl_block(self, data, seq, timeout=DEFAULT_TIMEOUT):
  531. self.check_command("write compressed data to flash after seq %d" % seq,
  532. self.ESP_FLASH_DEFL_DATA, struct.pack('<IIII', len(data), seq, 0, 0) + data, self.checksum(data), timeout=timeout)
  533. """ Leave compressed flash mode and run/reboot """
  534. @stub_and_esp32_function_only
  535. def flash_defl_finish(self, reboot=False):
  536. if not reboot and not self.IS_STUB:
  537. # skip sending flash_finish to ROM loader, as this
  538. # exits the bootloader. Stub doesn't do this.
  539. return
  540. pkt = struct.pack('<I', int(not reboot))
  541. self.check_command("leave compressed flash mode", self.ESP_FLASH_DEFL_END, pkt)
  542. self.in_bootloader = False
  543. @stub_and_esp32_function_only
  544. def flash_md5sum(self, addr, size):
  545. # the MD5 command returns additional bytes in the standard
  546. # command reply slot
  547. timeout = timeout_per_mb(MD5_TIMEOUT_PER_MB, size)
  548. res = self.check_command('calculate md5sum', self.ESP_SPI_FLASH_MD5, struct.pack('<IIII', addr, size, 0, 0),
  549. timeout=timeout)
  550. if len(res) == 32:
  551. return res.decode("utf-8") # already hex formatted
  552. elif len(res) == 16:
  553. return hexify(res).lower()
  554. else:
  555. raise FatalError("MD5Sum command returned unexpected result: %r" % res)
  556. @stub_and_esp32_function_only
  557. def change_baud(self, baud):
  558. print("Changing baud rate to %d" % baud)
  559. # stub takes the new baud rate and the old one
  560. second_arg = self._port.baudrate if self.IS_STUB else 0
  561. self.command(self.ESP_CHANGE_BAUDRATE, struct.pack('<II', baud, second_arg))
  562. print("Changed.")
  563. self._set_port_baudrate(baud)
  564. time.sleep(0.05) # get rid of crap sent during baud rate change
  565. self.flush_input()
  566. @stub_function_only
  567. def erase_flash(self):
  568. # depending on flash chip model the erase may take this long (maybe longer!)
  569. self.check_command("erase flash", self.ESP_ERASE_FLASH,
  570. timeout=CHIP_ERASE_TIMEOUT)
  571. @stub_function_only
  572. def erase_region(self, offset, size):
  573. if offset % self.FLASH_SECTOR_SIZE != 0:
  574. raise FatalError("Offset to erase from must be a multiple of 4096")
  575. if size % self.FLASH_SECTOR_SIZE != 0:
  576. raise FatalError("Size of data to erase must be a multiple of 4096")
  577. timeout = timeout_per_mb(ERASE_REGION_TIMEOUT_PER_MB, size)
  578. self.check_command("erase region", self.ESP_ERASE_REGION, struct.pack('<II', offset, size), timeout=timeout)
  579. @stub_function_only
  580. def read_flash(self, offset, length, progress_fn=None):
  581. # issue a standard bootloader command to trigger the read
  582. self.check_command("read flash", self.ESP_READ_FLASH,
  583. struct.pack('<IIII',
  584. offset,
  585. length,
  586. self.FLASH_SECTOR_SIZE,
  587. 64))
  588. # now we expect (length // block_size) SLIP frames with the data
  589. data = b''
  590. while len(data) < length:
  591. p = self.read()
  592. data += p
  593. if len(data) < length and len(p) < self.FLASH_SECTOR_SIZE:
  594. raise FatalError('Corrupt data, expected 0x%x bytes but received 0x%x bytes' % (self.FLASH_SECTOR_SIZE, len(p)))
  595. self.write(struct.pack('<I', len(data)))
  596. if progress_fn and (len(data) % 1024 == 0 or len(data) == length):
  597. progress_fn(len(data), length)
  598. if progress_fn:
  599. progress_fn(len(data), length)
  600. if len(data) > length:
  601. raise FatalError('Read more than expected')
  602. digest_frame = self.read()
  603. if len(digest_frame) != 16:
  604. raise FatalError('Expected digest, got: %s' % hexify(digest_frame))
  605. expected_digest = hexify(digest_frame).upper()
  606. digest = hashlib.md5(data).hexdigest().upper()
  607. if digest != expected_digest:
  608. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  609. return data
  610. def flash_spi_attach(self, hspi_arg):
  611. """Send SPI attach command to enable the SPI flash pins
  612. ESP8266 ROM does this when you send flash_begin, ESP32 ROM
  613. has it as a SPI command.
  614. """
  615. # last 3 bytes in ESP_SPI_ATTACH argument are reserved values
  616. arg = struct.pack('<I', hspi_arg)
  617. if not self.IS_STUB:
  618. # ESP32 ROM loader takes additional 'is legacy' arg, which is not
  619. # currently supported in the stub loader or esptool.py (as it's not usually needed.)
  620. is_legacy = 0
  621. arg += struct.pack('BBBB', is_legacy, 0, 0, 0)
  622. self.check_command("configure SPI flash pins", ESP32ROM.ESP_SPI_ATTACH, arg)
  623. def flash_set_parameters(self, size):
  624. """Tell the ESP bootloader the parameters of the chip
  625. Corresponds to the "flashchip" data structure that the ROM
  626. has in RAM.
  627. 'size' is in bytes.
  628. All other flash parameters are currently hardcoded (on ESP8266
  629. these are mostly ignored by ROM code, on ESP32 I'm not sure.)
  630. """
  631. fl_id = 0
  632. total_size = size
  633. block_size = 64 * 1024
  634. sector_size = 4 * 1024
  635. page_size = 256
  636. status_mask = 0xffff
  637. self.check_command("set SPI params", ESP32ROM.ESP_SPI_SET_PARAMS,
  638. struct.pack('<IIIIII', fl_id, total_size, block_size, sector_size, page_size, status_mask))
  639. def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
  640. """Run an arbitrary SPI flash command.
  641. This function uses the "USR_COMMAND" functionality in the ESP
  642. SPI hardware, rather than the precanned commands supported by
  643. hardware. So the value of spiflash_command is an actual command
  644. byte, sent over the wire.
  645. After writing command byte, writes 'data' to MOSI and then
  646. reads back 'read_bits' of reply on MISO. Result is a number.
  647. """
  648. # SPI_USR register flags
  649. SPI_USR_COMMAND = (1 << 31)
  650. SPI_USR_MISO = (1 << 28)
  651. SPI_USR_MOSI = (1 << 27)
  652. # SPI registers, base address differs ESP32 vs 8266
  653. base = self.SPI_REG_BASE
  654. SPI_CMD_REG = base + 0x00
  655. SPI_USR_REG = base + 0x1C
  656. SPI_USR1_REG = base + 0x20
  657. SPI_USR2_REG = base + 0x24
  658. SPI_W0_REG = base + self.SPI_W0_OFFS
  659. # following two registers are ESP32 only
  660. if self.SPI_HAS_MOSI_DLEN_REG:
  661. # ESP32 has a more sophisticated wayto set up "user" commands
  662. def set_data_lengths(mosi_bits, miso_bits):
  663. SPI_MOSI_DLEN_REG = base + 0x28
  664. SPI_MISO_DLEN_REG = base + 0x2C
  665. if mosi_bits > 0:
  666. self.write_reg(SPI_MOSI_DLEN_REG, mosi_bits - 1)
  667. if miso_bits > 0:
  668. self.write_reg(SPI_MISO_DLEN_REG, miso_bits - 1)
  669. else:
  670. def set_data_lengths(mosi_bits, miso_bits):
  671. SPI_DATA_LEN_REG = SPI_USR1_REG
  672. SPI_MOSI_BITLEN_S = 17
  673. SPI_MISO_BITLEN_S = 8
  674. mosi_mask = 0 if (mosi_bits == 0) else (mosi_bits - 1)
  675. miso_mask = 0 if (miso_bits == 0) else (miso_bits - 1)
  676. self.write_reg(SPI_DATA_LEN_REG,
  677. (miso_mask << SPI_MISO_BITLEN_S) | (
  678. mosi_mask << SPI_MOSI_BITLEN_S))
  679. # SPI peripheral "command" bitmasks for SPI_CMD_REG
  680. SPI_CMD_USR = (1 << 18)
  681. # shift values
  682. SPI_USR2_DLEN_SHIFT = 28
  683. if read_bits > 32:
  684. raise FatalError("Reading more than 32 bits back from a SPI flash operation is unsupported")
  685. if len(data) > 64:
  686. raise FatalError("Writing more than 64 bytes of data with one SPI command is unsupported")
  687. data_bits = len(data) * 8
  688. old_spi_usr = self.read_reg(SPI_USR_REG)
  689. old_spi_usr2 = self.read_reg(SPI_USR2_REG)
  690. flags = SPI_USR_COMMAND
  691. if read_bits > 0:
  692. flags |= SPI_USR_MISO
  693. if data_bits > 0:
  694. flags |= SPI_USR_MOSI
  695. set_data_lengths(data_bits, read_bits)
  696. self.write_reg(SPI_USR_REG, flags)
  697. self.write_reg(SPI_USR2_REG,
  698. (7 << SPI_USR2_DLEN_SHIFT) | spiflash_command)
  699. if data_bits == 0:
  700. self.write_reg(SPI_W0_REG, 0) # clear data register before we read it
  701. else:
  702. data = pad_to(data, 4, b'\00') # pad to 32-bit multiple
  703. words = struct.unpack("I" * (len(data) // 4), data)
  704. next_reg = SPI_W0_REG
  705. for word in words:
  706. self.write_reg(next_reg, word)
  707. next_reg += 4
  708. self.write_reg(SPI_CMD_REG, SPI_CMD_USR)
  709. def wait_done():
  710. for _ in range(10):
  711. if (self.read_reg(SPI_CMD_REG) & SPI_CMD_USR) == 0:
  712. return
  713. raise FatalError("SPI command did not complete in time")
  714. wait_done()
  715. status = self.read_reg(SPI_W0_REG)
  716. # restore some SPI controller registers
  717. self.write_reg(SPI_USR_REG, old_spi_usr)
  718. self.write_reg(SPI_USR2_REG, old_spi_usr2)
  719. return status
  720. def read_status(self, num_bytes=2):
  721. """Read up to 24 bits (num_bytes) of SPI flash status register contents
  722. via RDSR, RDSR2, RDSR3 commands
  723. Not all SPI flash supports all three commands. The upper 1 or 2
  724. bytes may be 0xFF.
  725. """
  726. SPIFLASH_RDSR = 0x05
  727. SPIFLASH_RDSR2 = 0x35
  728. SPIFLASH_RDSR3 = 0x15
  729. status = 0
  730. shift = 0
  731. for cmd in [SPIFLASH_RDSR, SPIFLASH_RDSR2, SPIFLASH_RDSR3][0:num_bytes]:
  732. status += self.run_spiflash_command(cmd, read_bits=8) << shift
  733. shift += 8
  734. return status
  735. def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
  736. """Write up to 24 bits (num_bytes) of new status register
  737. num_bytes can be 1, 2 or 3.
  738. Not all flash supports the additional commands to write the
  739. second and third byte of the status register. When writing 2
  740. bytes, esptool also sends a 16-byte WRSR command (as some
  741. flash types use this instead of WRSR2.)
  742. If the set_non_volatile flag is set, non-volatile bits will
  743. be set as well as volatile ones (WREN used instead of WEVSR).
  744. """
  745. SPIFLASH_WRSR = 0x01
  746. SPIFLASH_WRSR2 = 0x31
  747. SPIFLASH_WRSR3 = 0x11
  748. SPIFLASH_WEVSR = 0x50
  749. SPIFLASH_WREN = 0x06
  750. SPIFLASH_WRDI = 0x04
  751. enable_cmd = SPIFLASH_WREN if set_non_volatile else SPIFLASH_WEVSR
  752. # try using a 16-bit WRSR (not supported by all chips)
  753. # this may be redundant, but shouldn't hurt
  754. if num_bytes == 2:
  755. self.run_spiflash_command(enable_cmd)
  756. self.run_spiflash_command(SPIFLASH_WRSR, struct.pack("<H", new_status))
  757. # also try using individual commands (also not supported by all chips for num_bytes 2 & 3)
  758. for cmd in [SPIFLASH_WRSR, SPIFLASH_WRSR2, SPIFLASH_WRSR3][0:num_bytes]:
  759. self.run_spiflash_command(enable_cmd)
  760. self.run_spiflash_command(cmd, struct.pack("B", new_status & 0xFF))
  761. new_status >>= 8
  762. self.run_spiflash_command(SPIFLASH_WRDI)
  763. def hard_reset(self):
  764. self._setRTS(True) # EN->LOW
  765. time.sleep(0.1)
  766. self._setRTS(False)
  767. def soft_reset(self, stay_in_bootloader):
  768. if not self.IS_STUB:
  769. if stay_in_bootloader:
  770. return # ROM bootloader is already in bootloader!
  771. else:
  772. # 'run user code' is as close to a soft reset as we can do
  773. self.flash_begin(0, 0)
  774. self.flash_finish(False)
  775. else:
  776. if stay_in_bootloader:
  777. # soft resetting from the stub loader
  778. # will re-load the ROM bootloader
  779. self.flash_begin(0, 0)
  780. self.flash_finish(True)
  781. elif self.CHIP_NAME != "ESP8266":
  782. raise FatalError("Soft resetting is currently only supported on ESP8266")
  783. else:
  784. # running user code from stub loader requires some hacks
  785. # in the stub loader
  786. self.command(self.ESP_RUN_USER_CODE, wait_response=False)
  787. class ESP8266ROM(ESPLoader):
  788. """ Access class for ESP8266 ROM bootloader
  789. """
  790. CHIP_NAME = "ESP8266"
  791. IS_STUB = False
  792. DATE_REG_VALUE = 0x00062000
  793. # OTP ROM addresses
  794. ESP_OTP_MAC0 = 0x3ff00050
  795. ESP_OTP_MAC1 = 0x3ff00054
  796. ESP_OTP_MAC3 = 0x3ff0005c
  797. SPI_REG_BASE = 0x60000200
  798. SPI_W0_OFFS = 0x40
  799. SPI_HAS_MOSI_DLEN_REG = False
  800. FLASH_SIZES = {
  801. '512KB':0x00,
  802. '256KB':0x10,
  803. '1MB':0x20,
  804. '2MB':0x30,
  805. '4MB':0x40,
  806. '2MB-c1': 0x50,
  807. '4MB-c1':0x60,
  808. '8MB':0x80,
  809. '16MB':0x90,
  810. }
  811. BOOTLOADER_FLASH_OFFSET = 0
  812. def get_efuses(self):
  813. # Return the 128 bits of ESP8266 efuse as a single Python integer
  814. return (self.read_reg(0x3ff0005c) << 96 |
  815. self.read_reg(0x3ff00058) << 64 |
  816. self.read_reg(0x3ff00054) << 32 |
  817. self.read_reg(0x3ff00050))
  818. def get_chip_description(self):
  819. efuses = self.get_efuses()
  820. is_8285 = (efuses & ((1 << 4) | 1 << 80)) != 0 # One or the other efuse bit is set for ESP8285
  821. return "ESP8285" if is_8285 else "ESP8266EX"
  822. def get_chip_features(self):
  823. features = ["WiFi"]
  824. if self.get_chip_description() == "ESP8285":
  825. features += ["Embedded Flash"]
  826. return features
  827. def flash_spi_attach(self, hspi_arg):
  828. if self.IS_STUB:
  829. super(ESP8266ROM, self).flash_spi_attach(hspi_arg)
  830. else:
  831. # ESP8266 ROM has no flash_spi_attach command in serial protocol,
  832. # but flash_begin will do it
  833. self.flash_begin(0, 0)
  834. def flash_set_parameters(self, size):
  835. # not implemented in ROM, but OK to silently skip for ROM
  836. if self.IS_STUB:
  837. super(ESP8266ROM, self).flash_set_parameters(size)
  838. def chip_id(self):
  839. """ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """
  840. id0 = self.read_reg(self.ESP_OTP_MAC0)
  841. id1 = self.read_reg(self.ESP_OTP_MAC1)
  842. return (id0 >> 24) | ((id1 & MAX_UINT24) << 8)
  843. def read_mac(self):
  844. """ Read MAC from OTP ROM """
  845. mac0 = self.read_reg(self.ESP_OTP_MAC0)
  846. mac1 = self.read_reg(self.ESP_OTP_MAC1)
  847. mac3 = self.read_reg(self.ESP_OTP_MAC3)
  848. if (mac3 != 0):
  849. oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
  850. elif ((mac1 >> 16) & 0xff) == 0:
  851. oui = (0x18, 0xfe, 0x34)
  852. elif ((mac1 >> 16) & 0xff) == 1:
  853. oui = (0xac, 0xd0, 0x74)
  854. else:
  855. raise FatalError("Unknown OUI")
  856. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  857. def get_erase_size(self, offset, size):
  858. """ Calculate an erase size given a specific size in bytes.
  859. Provides a workaround for the bootloader erase bug."""
  860. sectors_per_block = 16
  861. sector_size = self.FLASH_SECTOR_SIZE
  862. num_sectors = (size + sector_size - 1) // sector_size
  863. start_sector = offset // sector_size
  864. head_sectors = sectors_per_block - (start_sector % sectors_per_block)
  865. if num_sectors < head_sectors:
  866. head_sectors = num_sectors
  867. if num_sectors < 2 * head_sectors:
  868. return (num_sectors + 1) // 2 * sector_size
  869. else:
  870. return (num_sectors - head_sectors) * sector_size
  871. def override_vddsdio(self, new_voltage):
  872. raise NotImplementedInROMError("Overriding VDDSDIO setting only applies to ESP32")
  873. class ESP8266StubLoader(ESP8266ROM):
  874. """ Access class for ESP8266 stub loader, runs on top of ROM.
  875. """
  876. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  877. IS_STUB = True
  878. def __init__(self, rom_loader):
  879. self._port = rom_loader._port
  880. self._trace_enabled = rom_loader._trace_enabled
  881. self.flush_input() # resets _slip_reader
  882. def get_erase_size(self, offset, size):
  883. return size # stub doesn't have same size bug as ROM loader
  884. ESP8266ROM.STUB_CLASS = ESP8266StubLoader
  885. class ESP32ROM(ESPLoader):
  886. """Access class for ESP32 ROM bootloader
  887. """
  888. CHIP_NAME = "ESP32"
  889. IS_STUB = False
  890. DATE_REG_VALUE = 0x15122500
  891. IROM_MAP_START = 0x400d0000
  892. IROM_MAP_END = 0x40400000
  893. DROM_MAP_START = 0x3F400000
  894. DROM_MAP_END = 0x3F800000
  895. # ESP32 uses a 4 byte status reply
  896. STATUS_BYTES_LENGTH = 4
  897. SPI_REG_BASE = 0x60002000
  898. EFUSE_REG_BASE = 0x6001a000
  899. SPI_W0_OFFS = 0x80
  900. SPI_HAS_MOSI_DLEN_REG = True
  901. FLASH_SIZES = {
  902. '1MB':0x00,
  903. '2MB':0x10,
  904. '4MB':0x20,
  905. '8MB':0x30,
  906. '16MB':0x40
  907. }
  908. BOOTLOADER_FLASH_OFFSET = 0x1000
  909. OVERRIDE_VDDSDIO_CHOICES = ["1.8V", "1.9V", "OFF"]
  910. def get_chip_description(self):
  911. word3 = self.read_efuse(3)
  912. chip_ver_rev1 = (word3 >> 15) & 0x1
  913. pkg_version = (word3 >> 9) & 0x07
  914. chip_name = {
  915. 0: "ESP32D0WDQ6",
  916. 1: "ESP32D0WDQ5",
  917. 2: "ESP32D2WDQ5",
  918. 5: "ESP32-PICO-D4",
  919. }.get(pkg_version, "unknown ESP32")
  920. return "%s (revision %d)" % (chip_name, chip_ver_rev1)
  921. def get_chip_features(self):
  922. features = ["WiFi"]
  923. word3 = self.read_efuse(3)
  924. # names of variables in this section are lowercase
  925. # versions of EFUSE names as documented in TRM and
  926. # ESP-IDF efuse_reg.h
  927. chip_ver_dis_bt = word3 & (1 << 1)
  928. if chip_ver_dis_bt == 0:
  929. features += ["BT"]
  930. chip_ver_dis_app_cpu = word3 & (1 << 0)
  931. if chip_ver_dis_app_cpu:
  932. features += ["Single Core"]
  933. else:
  934. features += ["Dual Core"]
  935. chip_cpu_freq_rated = word3 & (1 << 13)
  936. if chip_cpu_freq_rated:
  937. chip_cpu_freq_low = word3 & (1 << 12)
  938. if chip_cpu_freq_low:
  939. features += ["160MHz"]
  940. else:
  941. features += ["240MHz"]
  942. pkg_version = (word3 >> 9) & 0x07
  943. if pkg_version in [2, 4, 5]:
  944. features += ["Embedded Flash"]
  945. word4 = self.read_efuse(4)
  946. adc_vref = (word4 >> 8) & 0x1F
  947. if adc_vref:
  948. features += ["VRef calibration in efuse"]
  949. blk3_part_res = word3 >> 14 & 0x1
  950. if blk3_part_res:
  951. features += ["BLK3 partially reserved"]
  952. word6 = self.read_efuse(6)
  953. coding_scheme = word6 & 0x3
  954. features += ["Coding Scheme %s" % {
  955. 0: "None",
  956. 1: "3/4",
  957. 2: "Repeat (UNSUPPORTED)",
  958. 3: "Invalid"}[coding_scheme]]
  959. return features
  960. def read_efuse(self, n):
  961. """ Read the nth word of the ESP3x EFUSE region. """
  962. return self.read_reg(self.EFUSE_REG_BASE + (4 * n))
  963. def chip_id(self):
  964. raise NotSupportedError(self, "chip_id")
  965. def read_mac(self):
  966. """ Read MAC from EFUSE region """
  967. words = [self.read_efuse(2), self.read_efuse(1)]
  968. bitstring = struct.pack(">II", *words)
  969. bitstring = bitstring[2:8] # trim the 2 byte CRC
  970. try:
  971. return tuple(ord(b) for b in bitstring)
  972. except TypeError: # Python 3, bitstring elements are already bytes
  973. return tuple(bitstring)
  974. def get_erase_size(self, offset, size):
  975. return size
  976. def override_vddsdio(self, new_voltage):
  977. new_voltage = new_voltage.upper()
  978. if new_voltage not in self.OVERRIDE_VDDSDIO_CHOICES:
  979. raise FatalError("The only accepted VDDSDIO overrides are '1.8V', '1.9V' and 'OFF'")
  980. RTC_CNTL_SDIO_CONF_REG = 0x3ff48074
  981. RTC_CNTL_XPD_SDIO_REG = (1 << 31)
  982. RTC_CNTL_DREFH_SDIO_M = (3 << 29)
  983. RTC_CNTL_DREFM_SDIO_M = (3 << 27)
  984. RTC_CNTL_DREFL_SDIO_M = (3 << 25)
  985. # RTC_CNTL_SDIO_TIEH = (1 << 23) # not used here, setting TIEH=1 would set 3.3V output, not safe for esptool.py to do
  986. RTC_CNTL_SDIO_FORCE = (1 << 22)
  987. RTC_CNTL_SDIO_PD_EN = (1 << 21)
  988. reg_val = RTC_CNTL_SDIO_FORCE # override efuse setting
  989. reg_val |= RTC_CNTL_SDIO_PD_EN
  990. if new_voltage != "OFF":
  991. reg_val |= RTC_CNTL_XPD_SDIO_REG # enable internal LDO
  992. if new_voltage == "1.9V":
  993. reg_val |= (RTC_CNTL_DREFH_SDIO_M | RTC_CNTL_DREFM_SDIO_M | RTC_CNTL_DREFL_SDIO_M) # boost voltage
  994. self.write_reg(RTC_CNTL_SDIO_CONF_REG, reg_val)
  995. print("VDDSDIO regulator set to %s" % new_voltage)
  996. class ESP32StubLoader(ESP32ROM):
  997. """ Access class for ESP32 stub loader, runs on top of ROM.
  998. """
  999. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  1000. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  1001. IS_STUB = True
  1002. def __init__(self, rom_loader):
  1003. self._port = rom_loader._port
  1004. self._trace_enabled = rom_loader._trace_enabled
  1005. self.flush_input() # resets _slip_reader
  1006. ESP32ROM.STUB_CLASS = ESP32StubLoader
  1007. class ESPBOOTLOADER(object):
  1008. """ These are constants related to software ESP bootloader, working with 'v2' image files """
  1009. # First byte of the "v2" application image
  1010. IMAGE_V2_MAGIC = 0xea
  1011. # First 'segment' value in a "v2" application image, appears to be a constant version value?
  1012. IMAGE_V2_SEGMENT = 4
  1013. def LoadFirmwareImage(chip, filename):
  1014. """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
  1015. original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
  1016. Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2).
  1017. """
  1018. with open(filename, 'rb') as f:
  1019. if chip.lower() == 'esp32':
  1020. return ESP32FirmwareImage(f)
  1021. else: # Otherwise, ESP8266 so look at magic to determine the image type
  1022. magic = ord(f.read(1))
  1023. f.seek(0)
  1024. if magic == ESPLoader.ESP_IMAGE_MAGIC:
  1025. return ESP8266ROMFirmwareImage(f)
  1026. elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
  1027. return ESP8266V2FirmwareImage(f)
  1028. else:
  1029. raise FatalError("Invalid image magic number: %d" % magic)
  1030. class ImageSegment(object):
  1031. """ Wrapper class for a segment in an ESP image
  1032. (very similar to a section in an ELFImage also) """
  1033. def __init__(self, addr, data, file_offs=None):
  1034. self.addr = addr
  1035. self.data = data
  1036. self.file_offs = file_offs
  1037. self.include_in_checksum = True
  1038. if self.addr != 0:
  1039. self.pad_to_alignment(4) # pad all "real" ImageSegments 4 byte aligned length
  1040. def copy_with_new_addr(self, new_addr):
  1041. """ Return a new ImageSegment with same data, but mapped at
  1042. a new address. """
  1043. return ImageSegment(new_addr, self.data, 0)
  1044. def split_image(self, split_len):
  1045. """ Return a new ImageSegment which splits "split_len" bytes
  1046. from the beginning of the data. Remaining bytes are kept in
  1047. this segment object (and the start address is adjusted to match.) """
  1048. result = copy.copy(self)
  1049. result.data = self.data[:split_len]
  1050. self.data = self.data[split_len:]
  1051. self.addr += split_len
  1052. self.file_offs = None
  1053. result.file_offs = None
  1054. return result
  1055. def __repr__(self):
  1056. r = "len 0x%05x load 0x%08x" % (len(self.data), self.addr)
  1057. if self.file_offs is not None:
  1058. r += " file_offs 0x%08x" % (self.file_offs)
  1059. return r
  1060. def pad_to_alignment(self, alignment):
  1061. self.data = pad_to(self.data, alignment, b'\x00')
  1062. class ELFSection(ImageSegment):
  1063. """ Wrapper class for a section in an ELF image, has a section
  1064. name as well as the common properties of an ImageSegment. """
  1065. def __init__(self, name, addr, data):
  1066. super(ELFSection, self).__init__(addr, data)
  1067. self.name = name.decode("utf-8")
  1068. def __repr__(self):
  1069. return "%s %s" % (self.name, super(ELFSection, self).__repr__())
  1070. class BaseFirmwareImage(object):
  1071. SEG_HEADER_LEN = 8
  1072. SHA256_DIGEST_LEN = 32
  1073. """ Base class with common firmware image functions """
  1074. def __init__(self):
  1075. self.segments = []
  1076. self.entrypoint = 0
  1077. self.elf_sha256 = None
  1078. self.elf_sha256_offset = 0
  1079. def load_common_header(self, load_file, expected_magic):
  1080. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  1081. if magic != expected_magic:
  1082. raise FatalError('Invalid firmware image magic=0x%x' % (magic))
  1083. return segments
  1084. def verify(self):
  1085. if len(self.segments) > 16:
  1086. raise FatalError('Invalid segment count %d (max 16). Usually this indicates a linker script problem.' % len(self.segments))
  1087. def load_segment(self, f, is_irom_segment=False):
  1088. """ Load the next segment from the image file """
  1089. file_offs = f.tell()
  1090. (offset, size) = struct.unpack('<II', f.read(8))
  1091. self.warn_if_unusual_segment(offset, size, is_irom_segment)
  1092. segment_data = f.read(size)
  1093. if len(segment_data) < size:
  1094. raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
  1095. segment = ImageSegment(offset, segment_data, file_offs)
  1096. self.segments.append(segment)
  1097. return segment
  1098. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  1099. if not is_irom_segment:
  1100. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  1101. print('WARNING: Suspicious segment 0x%x, length %d' % (offset, size))
  1102. def maybe_patch_segment_data(self, f, segment_data):
  1103. """If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data."""
  1104. segment_len = len(segment_data)
  1105. file_pos = f.tell()
  1106. if self.elf_sha256_offset >= file_pos and self.elf_sha256_offset < file_pos + segment_len:
  1107. # SHA256 digest needs to be patched into this segment,
  1108. # calculate offset of the digest inside the segment.
  1109. patch_offset = self.elf_sha256_offset - file_pos
  1110. # Sanity checks
  1111. if patch_offset < self.SEG_HEADER_LEN or patch_offset + self.SHA256_DIGEST_LEN > segment_len:
  1112. raise FatalError('Can not place SHA256 digest on segment boundary' +
  1113. '(elf_sha256_offset=%d, file_pos=%d, segment_size=%d)' %
  1114. (self.elf_sha256_offset, file_pos, segment_len))
  1115. assert(len(self.elf_sha256) == self.SHA256_DIGEST_LEN)
  1116. # offset relative to the data part
  1117. patch_offset -= self.SEG_HEADER_LEN
  1118. segment_data = segment_data[0:patch_offset] + self.elf_sha256 + \
  1119. segment_data[patch_offset + self.SHA256_DIGEST_LEN:]
  1120. return segment_data
  1121. def save_segment(self, f, segment, checksum=None):
  1122. """ Save the next segment to the image file, return next checksum value if provided """
  1123. segment_data = self.maybe_patch_segment_data(f, segment.data)
  1124. f.write(struct.pack('<II', segment.addr, len(segment_data)))
  1125. f.write(segment_data)
  1126. if checksum is not None:
  1127. return ESPLoader.checksum(segment_data, checksum)
  1128. def read_checksum(self, f):
  1129. """ Return ESPLoader checksum from end of just-read image """
  1130. # Skip the padding. The checksum is stored in the last byte so that the
  1131. # file is a multiple of 16 bytes.
  1132. align_file_position(f, 16)
  1133. return ord(f.read(1))
  1134. def calculate_checksum(self):
  1135. """ Calculate checksum of loaded image, based on segments in
  1136. segment array.
  1137. """
  1138. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1139. for seg in self.segments:
  1140. if seg.include_in_checksum:
  1141. checksum = ESPLoader.checksum(seg.data, checksum)
  1142. return checksum
  1143. def append_checksum(self, f, checksum):
  1144. """ Append ESPLoader checksum to the just-written image """
  1145. align_file_position(f, 16)
  1146. f.write(struct.pack(b'B', checksum))
  1147. def write_common_header(self, f, segments):
  1148. f.write(struct.pack('<BBBBI', ESPLoader.ESP_IMAGE_MAGIC, len(segments),
  1149. self.flash_mode, self.flash_size_freq, self.entrypoint))
  1150. def is_irom_addr(self, addr):
  1151. """ Returns True if an address starts in the irom region.
  1152. Valid for ESP8266 only.
  1153. """
  1154. return ESP8266ROM.IROM_MAP_START <= addr < ESP8266ROM.IROM_MAP_END
  1155. def get_irom_segment(self):
  1156. irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)]
  1157. if len(irom_segments) > 0:
  1158. if len(irom_segments) != 1:
  1159. raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
  1160. return irom_segments[0]
  1161. return None
  1162. def get_non_irom_segments(self):
  1163. irom_segment = self.get_irom_segment()
  1164. return [s for s in self.segments if s != irom_segment]
  1165. class ESP8266ROMFirmwareImage(BaseFirmwareImage):
  1166. """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
  1167. ROM_LOADER = ESP8266ROM
  1168. def __init__(self, load_file=None):
  1169. super(ESP8266ROMFirmwareImage, self).__init__()
  1170. self.flash_mode = 0
  1171. self.flash_size_freq = 0
  1172. self.version = 1
  1173. if load_file is not None:
  1174. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  1175. for _ in range(segments):
  1176. self.load_segment(load_file)
  1177. self.checksum = self.read_checksum(load_file)
  1178. self.verify()
  1179. def default_output_name(self, input_file):
  1180. """ Derive a default output name from the ELF name. """
  1181. return input_file + '-'
  1182. def save(self, basename):
  1183. """ Save a set of V1 images for flashing. Parameter is a base filename. """
  1184. # IROM data goes in its own plain binary file
  1185. irom_segment = self.get_irom_segment()
  1186. if irom_segment is not None:
  1187. with open("%s0x%05x.bin" % (basename, irom_segment.addr - ESP8266ROM.IROM_MAP_START), "wb") as f:
  1188. f.write(irom_segment.data)
  1189. # everything but IROM goes at 0x00000 in an image file
  1190. normal_segments = self.get_non_irom_segments()
  1191. with open("%s0x00000.bin" % basename, 'wb') as f:
  1192. self.write_common_header(f, normal_segments)
  1193. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1194. for segment in normal_segments:
  1195. checksum = self.save_segment(f, segment, checksum)
  1196. self.append_checksum(f, checksum)
  1197. class ESP8266V2FirmwareImage(BaseFirmwareImage):
  1198. """ 'Version 2' firmware image, segments loaded by software bootloader stub
  1199. (ie Espressif bootloader or rboot)
  1200. """
  1201. ROM_LOADER = ESP8266ROM
  1202. def __init__(self, load_file=None):
  1203. super(ESP8266V2FirmwareImage, self).__init__()
  1204. self.version = 2
  1205. if load_file is not None:
  1206. segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC)
  1207. if segments != ESPBOOTLOADER.IMAGE_V2_SEGMENT:
  1208. # segment count is not really segment count here, but we expect to see '4'
  1209. print('Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments)
  1210. # irom segment comes before the second header
  1211. #
  1212. # the file is saved in the image with a zero load address
  1213. # in the header, so we need to calculate a load address
  1214. irom_segment = self.load_segment(load_file, True)
  1215. irom_segment.addr = 0 # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_addr + 8
  1216. irom_segment.include_in_checksum = False
  1217. first_flash_mode = self.flash_mode
  1218. first_flash_size_freq = self.flash_size_freq
  1219. first_entrypoint = self.entrypoint
  1220. # load the second header
  1221. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  1222. if first_flash_mode != self.flash_mode:
  1223. print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  1224. % (first_flash_mode, self.flash_mode))
  1225. if first_flash_size_freq != self.flash_size_freq:
  1226. print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  1227. % (first_flash_size_freq, self.flash_size_freq))
  1228. if first_entrypoint != self.entrypoint:
  1229. print('WARNING: Entrypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
  1230. % (first_entrypoint, self.entrypoint))
  1231. # load all the usual segments
  1232. for _ in range(segments):
  1233. self.load_segment(load_file)
  1234. self.checksum = self.read_checksum(load_file)
  1235. self.verify()
  1236. def default_output_name(self, input_file):
  1237. """ Derive a default output name from the ELF name. """
  1238. irom_segment = self.get_irom_segment()
  1239. if irom_segment is not None:
  1240. irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
  1241. else:
  1242. irom_offs = 0
  1243. return "%s-0x%05x.bin" % (os.path.splitext(input_file)[0],
  1244. irom_offs & ~(ESPLoader.FLASH_SECTOR_SIZE - 1))
  1245. def save(self, filename):
  1246. with open(filename, 'wb') as f:
  1247. # Save first header for irom0 segment
  1248. f.write(struct.pack(b'<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
  1249. self.flash_mode, self.flash_size_freq, self.entrypoint))
  1250. irom_segment = self.get_irom_segment()
  1251. if irom_segment is not None:
  1252. # save irom0 segment, make sure it has load addr 0 in the file
  1253. irom_segment = irom_segment.copy_with_new_addr(0)
  1254. irom_segment.pad_to_alignment(16) # irom_segment must end on a 16 byte boundary
  1255. self.save_segment(f, irom_segment)
  1256. # second header, matches V1 header and contains loadable segments
  1257. normal_segments = self.get_non_irom_segments()
  1258. self.write_common_header(f, normal_segments)
  1259. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1260. for segment in normal_segments:
  1261. checksum = self.save_segment(f, segment, checksum)
  1262. self.append_checksum(f, checksum)
  1263. # calculate a crc32 of entire file and append
  1264. # (algorithm used by recent 8266 SDK bootloaders)
  1265. with open(filename, 'rb') as f:
  1266. crc = esp8266_crc32(f.read())
  1267. with open(filename, 'ab') as f:
  1268. f.write(struct.pack(b'<I', crc))
  1269. # Backwards compatibility for previous API, remove in esptool.py V3
  1270. ESPFirmwareImage = ESP8266ROMFirmwareImage
  1271. OTAFirmwareImage = ESP8266V2FirmwareImage
  1272. def esp8266_crc32(data):
  1273. """
  1274. CRC32 algorithm used by 8266 SDK bootloader (and gen_appbin.py).
  1275. """
  1276. crc = binascii.crc32(data, 0) & 0xFFFFFFFF
  1277. if crc & 0x80000000:
  1278. return crc ^ 0xFFFFFFFF
  1279. else:
  1280. return crc + 1
  1281. class ESP32FirmwareImage(BaseFirmwareImage):
  1282. """ ESP32 firmware image is very similar to V1 ESP8266 image,
  1283. except with an additional 16 byte reserved header at top of image,
  1284. and because of new flash mapping capabilities the flash-mapped regions
  1285. can be placed in the normal image (just @ 64kB padded offsets).
  1286. """
  1287. ROM_LOADER = ESP32ROM
  1288. # ROM bootloader will read the wp_pin field if SPI flash
  1289. # pins are remapped via flash. IDF actually enables QIO only
  1290. # from software bootloader, so this can be ignored. But needs
  1291. # to be set to this value so ROM bootloader will skip it.
  1292. WP_PIN_DISABLED = 0xEE
  1293. EXTENDED_HEADER_STRUCT_FMT = "B" * 16
  1294. IROM_ALIGN = 65536
  1295. def __init__(self, load_file=None):
  1296. super(ESP32FirmwareImage, self).__init__()
  1297. self.secure_pad = False
  1298. self.flash_mode = 0
  1299. self.flash_size_freq = 0
  1300. self.version = 1
  1301. self.wp_pin = self.WP_PIN_DISABLED
  1302. # SPI pin drive levels
  1303. self.clk_drv = 0
  1304. self.q_drv = 0
  1305. self.d_drv = 0
  1306. self.cs_drv = 0
  1307. self.hd_drv = 0
  1308. self.wp_drv = 0
  1309. self.append_digest = True
  1310. if load_file is not None:
  1311. start = load_file.tell()
  1312. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  1313. self.load_extended_header(load_file)
  1314. for _ in range(segments):
  1315. self.load_segment(load_file)
  1316. self.checksum = self.read_checksum(load_file)
  1317. if self.append_digest:
  1318. end = load_file.tell()
  1319. self.stored_digest = load_file.read(32)
  1320. load_file.seek(start)
  1321. calc_digest = hashlib.sha256()
  1322. calc_digest.update(load_file.read(end - start))
  1323. self.calc_digest = calc_digest.digest() # TODO: decide what to do here?
  1324. self.verify()
  1325. def is_flash_addr(self, addr):
  1326. return (ESP32ROM.IROM_MAP_START <= addr < ESP32ROM.IROM_MAP_END) \
  1327. or (ESP32ROM.DROM_MAP_START <= addr < ESP32ROM.DROM_MAP_END)
  1328. def default_output_name(self, input_file):
  1329. """ Derive a default output name from the ELF name. """
  1330. return "%s.bin" % (os.path.splitext(input_file)[0])
  1331. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  1332. pass # TODO: add warnings for ESP32 segment offset/size combinations that are wrong
  1333. def save(self, filename):
  1334. total_segments = 0
  1335. with io.BytesIO() as f: # write file to memory first
  1336. self.write_common_header(f, self.segments)
  1337. # first 4 bytes of header are read by ROM bootloader for SPI
  1338. # config, but currently unused
  1339. self.save_extended_header(f)
  1340. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1341. # split segments into flash-mapped vs ram-loaded, and take copies so we can mutate them
  1342. flash_segments = [copy.deepcopy(s) for s in sorted(self.segments, key=lambda s:s.addr) if self.is_flash_addr(s.addr)]
  1343. ram_segments = [copy.deepcopy(s) for s in sorted(self.segments, key=lambda s:s.addr) if not self.is_flash_addr(s.addr)]
  1344. # check for multiple ELF sections that are mapped in the same flash mapping region.
  1345. # this is usually a sign of a broken linker script, but if you have a legitimate
  1346. # use case then let us know (we can merge segments here, but as a rule you probably
  1347. # want to merge them in your linker script.)
  1348. if len(flash_segments) > 0:
  1349. last_addr = flash_segments[0].addr
  1350. for segment in flash_segments[1:]:
  1351. if segment.addr // self.IROM_ALIGN == last_addr // self.IROM_ALIGN:
  1352. raise FatalError(("Segment loaded at 0x%08x lands in same 64KB flash mapping as segment loaded at 0x%08x. " +
  1353. "Can't generate binary. Suggest changing linker script or ELF to merge sections.") %
  1354. (segment.addr, last_addr))
  1355. last_addr = segment.addr
  1356. def get_alignment_data_needed(segment):
  1357. # Actual alignment (in data bytes) required for a segment header: positioned so that
  1358. # after we write the next 8 byte header, file_offs % IROM_ALIGN == segment.addr % IROM_ALIGN
  1359. #
  1360. # (this is because the segment's vaddr may not be IROM_ALIGNed, more likely is aligned
  1361. # IROM_ALIGN+0x18 to account for the binary file header
  1362. align_past = (segment.addr % self.IROM_ALIGN) - self.SEG_HEADER_LEN
  1363. pad_len = (self.IROM_ALIGN - (f.tell() % self.IROM_ALIGN)) + align_past
  1364. if pad_len == 0 or pad_len == self.IROM_ALIGN:
  1365. return 0 # already aligned
  1366. # subtract SEG_HEADER_LEN a second time, as the padding block has a header as well
  1367. pad_len -= self.SEG_HEADER_LEN
  1368. if pad_len < 0:
  1369. pad_len += self.IROM_ALIGN
  1370. return pad_len
  1371. # try to fit each flash segment on a 64kB aligned boundary
  1372. # by padding with parts of the non-flash segments...
  1373. while len(flash_segments) > 0:
  1374. segment = flash_segments[0]
  1375. pad_len = get_alignment_data_needed(segment)
  1376. if pad_len > 0: # need to pad
  1377. if len(ram_segments) > 0 and pad_len > self.SEG_HEADER_LEN:
  1378. pad_segment = ram_segments[0].split_image(pad_len)
  1379. if len(ram_segments[0].data) == 0:
  1380. ram_segments.pop(0)
  1381. else:
  1382. pad_segment = ImageSegment(0, b'\x00' * pad_len, f.tell())
  1383. checksum = self.save_segment(f, pad_segment, checksum)
  1384. total_segments += 1
  1385. else:
  1386. # write the flash segment
  1387. assert (f.tell() + 8) % self.IROM_ALIGN == segment.addr % self.IROM_ALIGN
  1388. checksum = self.save_flash_segment(f, segment, checksum)
  1389. flash_segments.pop(0)
  1390. total_segments += 1
  1391. # flash segments all written, so write any remaining RAM segments
  1392. for segment in ram_segments:
  1393. checksum = self.save_segment(f, segment, checksum)
  1394. total_segments += 1
  1395. if self.secure_pad:
  1396. # pad the image so that after signing it will end on a a 64KB boundary.
  1397. # This ensures all mapped flash content will be verified.
  1398. if not self.append_digest:
  1399. raise FatalError("secure_pad only applies if a SHA-256 digest is also appended to the image")
  1400. align_past = (f.tell() + self.SEG_HEADER_LEN) % self.IROM_ALIGN
  1401. # 16 byte aligned checksum (force the alignment to simplify calculations)
  1402. checksum_space = 16
  1403. # after checksum: SHA-256 digest + (to be added by signing process) version, signature + 12 trailing bytes due to alignment
  1404. space_after_checksum = 32 + 4 + 64 + 12
  1405. pad_len = (self.IROM_ALIGN - align_past - checksum_space - space_after_checksum) % self.IROM_ALIGN
  1406. pad_segment = ImageSegment(0, b'\x00' * pad_len, f.tell())
  1407. checksum = self.save_segment(f, pad_segment, checksum)
  1408. total_segments += 1
  1409. # done writing segments
  1410. self.append_checksum(f, checksum)
  1411. image_length = f.tell()
  1412. if self.secure_pad:
  1413. assert ((image_length + space_after_checksum) % self.IROM_ALIGN) == 0
  1414. # kinda hacky: go back to the initial header and write the new segment count
  1415. # that includes padding segments. This header is not checksummed
  1416. f.seek(1)
  1417. try:
  1418. f.write(chr(total_segments))
  1419. except TypeError: # Python 3
  1420. f.write(bytes([total_segments]))
  1421. if self.append_digest:
  1422. # calculate the SHA256 of the whole file and append it
  1423. f.seek(0)
  1424. digest = hashlib.sha256()
  1425. digest.update(f.read(image_length))
  1426. f.write(digest.digest())
  1427. with open(filename, 'wb') as real_file:
  1428. real_file.write(f.getvalue())
  1429. def save_flash_segment(self, f, segment, checksum=None):
  1430. """ Save the next segment to the image file, return next checksum value if provided """
  1431. segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN
  1432. segment_len_remainder = segment_end_pos % self.IROM_ALIGN
  1433. if segment_len_remainder < 0x24:
  1434. # Work around a bug in ESP-IDF 2nd stage bootloader, that it didn't map the
  1435. # last MMU page, if an IROM/DROM segment was < 0x24 bytes over the page boundary.
  1436. segment.data += b'\x00' * (0x24 - segment_len_remainder)
  1437. return self.save_segment(f, segment, checksum)
  1438. def load_extended_header(self, load_file):
  1439. def split_byte(n):
  1440. return (n & 0x0F, (n >> 4) & 0x0F)
  1441. fields = list(struct.unpack(self.EXTENDED_HEADER_STRUCT_FMT, load_file.read(16)))
  1442. self.wp_pin = fields[0]
  1443. # SPI pin drive stengths are two per byte
  1444. self.clk_drv, self.q_drv = split_byte(fields[1])
  1445. self.d_drv, self.cs_drv = split_byte(fields[2])
  1446. self.hd_drv, self.wp_drv = split_byte(fields[3])
  1447. if fields[15] in [0, 1]:
  1448. self.append_digest = (fields[15] == 1)
  1449. else:
  1450. raise RuntimeError("Invalid value for append_digest field (0x%02x). Should be 0 or 1.", fields[15])
  1451. # remaining fields in the middle should all be zero
  1452. if any(f for f in fields[4:15] if f != 0):
  1453. print("Warning: some reserved header fields have non-zero values. This image may be from a newer esptool.py?")
  1454. def save_extended_header(self, save_file):
  1455. def join_byte(ln,hn):
  1456. return (ln & 0x0F) + ((hn & 0x0F) << 4)
  1457. append_digest = 1 if self.append_digest else 0
  1458. fields = [self.wp_pin,
  1459. join_byte(self.clk_drv, self.q_drv),
  1460. join_byte(self.d_drv, self.cs_drv),
  1461. join_byte(self.hd_drv, self.wp_drv)]
  1462. fields += [0] * 11
  1463. fields += [append_digest]
  1464. packed = struct.pack(self.EXTENDED_HEADER_STRUCT_FMT, *fields)
  1465. save_file.write(packed)
  1466. class ELFFile(object):
  1467. SEC_TYPE_PROGBITS = 0x01
  1468. SEC_TYPE_STRTAB = 0x03
  1469. LEN_SEC_HEADER = 0x28
  1470. def __init__(self, name):
  1471. # Load sections from the ELF file
  1472. self.name = name
  1473. with open(self.name, 'rb') as f:
  1474. self._read_elf_file(f)
  1475. def get_section(self, section_name):
  1476. for s in self.sections:
  1477. if s.name == section_name:
  1478. return s
  1479. raise ValueError("No section %s in ELF file" % section_name)
  1480. def _read_elf_file(self, f):
  1481. # read the ELF file header
  1482. LEN_FILE_HEADER = 0x34
  1483. try:
  1484. (ident,_type,machine,_version,
  1485. self.entrypoint,_phoff,shoff,_flags,
  1486. _ehsize, _phentsize,_phnum, shentsize,
  1487. shnum,shstrndx) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
  1488. except struct.error as e:
  1489. raise FatalError("Failed to read a valid ELF header from %s: %s" % (self.name, e))
  1490. if byte(ident, 0) != 0x7f or ident[1:4] != b'ELF':
  1491. raise FatalError("%s has invalid ELF magic header" % self.name)
  1492. if machine != 0x5e:
  1493. raise FatalError("%s does not appear to be an Xtensa ELF file. e_machine=%04x" % (self.name, machine))
  1494. if shentsize != self.LEN_SEC_HEADER:
  1495. raise FatalError("%s has unexpected section header entry size 0x%x (not 0x28)" % (self.name, shentsize, self.LEN_SEC_HEADER))
  1496. if shnum == 0:
  1497. raise FatalError("%s has 0 section headers" % (self.name))
  1498. self._read_sections(f, shoff, shnum, shstrndx)
  1499. def _read_sections(self, f, section_header_offs, section_header_count, shstrndx):
  1500. f.seek(section_header_offs)
  1501. len_bytes = section_header_count * self.LEN_SEC_HEADER
  1502. section_header = f.read(len_bytes)
  1503. if len(section_header) == 0:
  1504. raise FatalError("No section header found at offset %04x in ELF file." % section_header_offs)
  1505. if len(section_header) != (len_bytes):
  1506. raise FatalError("Only read 0x%x bytes from section header (expected 0x%x.) Truncated ELF file?" % (len(section_header), len_bytes))
  1507. # walk through the section header and extract all sections
  1508. section_header_offsets = range(0, len(section_header), self.LEN_SEC_HEADER)
  1509. def read_section_header(offs):
  1510. name_offs,sec_type,_flags,lma,sec_offs,size = struct.unpack_from("<LLLLLL", section_header[offs:])
  1511. return (name_offs, sec_type, lma, size, sec_offs)
  1512. all_sections = [read_section_header(offs) for offs in section_header_offsets]
  1513. prog_sections = [s for s in all_sections if s[1] == ELFFile.SEC_TYPE_PROGBITS]
  1514. # search for the string table section
  1515. if not (shstrndx * self.LEN_SEC_HEADER) in section_header_offsets:
  1516. raise FatalError("ELF file has no STRTAB section at shstrndx %d" % shstrndx)
  1517. _,sec_type,_,sec_size,sec_offs = read_section_header(shstrndx * self.LEN_SEC_HEADER)
  1518. if sec_type != ELFFile.SEC_TYPE_STRTAB:
  1519. print('WARNING: ELF file has incorrect STRTAB section type 0x%02x' % sec_type)
  1520. f.seek(sec_offs)
  1521. string_table = f.read(sec_size)
  1522. # build the real list of ELFSections by reading the actual section names from the
  1523. # string table section, and actual data for each section from the ELF file itself
  1524. def lookup_string(offs):
  1525. raw = string_table[offs:]
  1526. return raw[:raw.index(b'\x00')]
  1527. def read_data(offs,size):
  1528. f.seek(offs)
  1529. return f.read(size)
  1530. prog_sections = [ELFSection(lookup_string(n_offs), lma, read_data(offs, size)) for (n_offs, _type, lma, size, offs) in prog_sections
  1531. if lma != 0 and size > 0]
  1532. self.sections = prog_sections
  1533. def sha256(self):
  1534. # return SHA256 hash of the input ELF file
  1535. sha256 = hashlib.sha256()
  1536. with open(self.name, 'rb') as f:
  1537. sha256.update(f.read())
  1538. return sha256.digest()
  1539. def slip_reader(port, trace_function):
  1540. """Generator to read SLIP packets from a serial port.
  1541. Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
  1542. Designed to avoid too many calls to serial.read(1), which can bog
  1543. down on slow systems.
  1544. """
  1545. partial_packet = None
  1546. in_escape = False
  1547. while True:
  1548. waiting = port.inWaiting()
  1549. read_bytes = port.read(1 if waiting == 0 else waiting)
  1550. if read_bytes == b'':
  1551. waiting_for = "header" if partial_packet is None else "content"
  1552. trace_function("Timed out waiting for packet %s", waiting_for)
  1553. raise FatalError("Timed out waiting for packet %s" % waiting_for)
  1554. trace_function("Read %d bytes: %s", len(read_bytes), HexFormatter(read_bytes))
  1555. for b in read_bytes:
  1556. if type(b) is int:
  1557. b = bytes([b]) # python 2/3 compat
  1558. if partial_packet is None: # waiting for packet header
  1559. if b == b'\xc0':
  1560. partial_packet = b""
  1561. else:
  1562. trace_function("Read invalid data: %s", HexFormatter(read_bytes))
  1563. trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting())))
  1564. raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
  1565. elif in_escape: # part-way through escape sequence
  1566. in_escape = False
  1567. if b == b'\xdc':
  1568. partial_packet += b'\xc0'
  1569. elif b == b'\xdd':
  1570. partial_packet += b'\xdb'
  1571. else:
  1572. trace_function("Read invalid data: %s", HexFormatter(read_bytes))
  1573. trace_function("Remaining data in serial buffer: %s", HexFormatter(port.read(port.inWaiting())))
  1574. raise FatalError('Invalid SLIP escape (0xdb, 0x%s)' % (hexify(b)))
  1575. elif b == b'\xdb': # start of escape sequence
  1576. in_escape = True
  1577. elif b == b'\xc0': # end of packet
  1578. trace_function("Received full packet: %s", HexFormatter(partial_packet))
  1579. yield partial_packet
  1580. partial_packet = None
  1581. else: # normal byte in packet
  1582. partial_packet += b
  1583. def arg_auto_int(x):
  1584. return int(x, 0)
  1585. def div_roundup(a, b):
  1586. """ Return a/b rounded up to nearest integer,
  1587. equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
  1588. without possible floating point accuracy errors.
  1589. """
  1590. return (int(a) + int(b) - 1) // int(b)
  1591. def align_file_position(f, size):
  1592. """ Align the position in the file to the next block of specified size """
  1593. align = (size - 1) - (f.tell() % size)
  1594. f.seek(align, 1)
  1595. def flash_size_bytes(size):
  1596. """ Given a flash size of the type passed in args.flash_size
  1597. (ie 512KB or 1MB) then return the size in bytes.
  1598. """
  1599. if "MB" in size:
  1600. return int(size[:size.index("MB")]) * 1024 * 1024
  1601. elif "KB" in size:
  1602. return int(size[:size.index("KB")]) * 1024
  1603. else:
  1604. raise FatalError("Unknown size %s" % size)
  1605. def hexify(s, uppercase=True):
  1606. format_str = '%02X' if uppercase else '%02x'
  1607. if not PYTHON2:
  1608. return ''.join(format_str % c for c in s)
  1609. else:
  1610. return ''.join(format_str % ord(c) for c in s)
  1611. class HexFormatter(object):
  1612. """
  1613. Wrapper class which takes binary data in its constructor
  1614. and returns a hex string as it's __str__ method.
  1615. This is intended for "lazy formatting" of trace() output
  1616. in hex format. Avoids overhead (significant on slow computers)
  1617. of generating long hex strings even if tracing is disabled.
  1618. Note that this doesn't save any overhead if passed as an
  1619. argument to "%", only when passed to trace()
  1620. If auto_split is set (default), any long line (> 16 bytes) will be
  1621. printed as separately indented lines, with ASCII decoding at the end
  1622. of each line.
  1623. """
  1624. def __init__(self, binary_string, auto_split=True):
  1625. self._s = binary_string
  1626. self._auto_split = auto_split
  1627. def __str__(self):
  1628. if self._auto_split and len(self._s) > 16:
  1629. result = ""
  1630. s = self._s
  1631. while len(s) > 0:
  1632. line = s[:16]
  1633. ascii_line = "".join(c if (c == ' ' or (c in string.printable and c not in string.whitespace))
  1634. else '.' for c in line.decode('ascii', 'replace'))
  1635. s = s[16:]
  1636. result += "\n %-16s %-16s | %s" % (hexify(line[:8], False), hexify(line[8:], False), ascii_line)
  1637. return result
  1638. else:
  1639. return hexify(self._s, False)
  1640. def pad_to(data, alignment, pad_character=b'\xFF'):
  1641. """ Pad to the next alignment boundary """
  1642. pad_mod = len(data) % alignment
  1643. if pad_mod != 0:
  1644. data += pad_character * (alignment - pad_mod)
  1645. return data
  1646. class FatalError(RuntimeError):
  1647. """
  1648. Wrapper class for runtime errors that aren't caused by internal bugs, but by
  1649. ESP8266 responses or input content.
  1650. """
  1651. def __init__(self, message):
  1652. RuntimeError.__init__(self, message)
  1653. @staticmethod
  1654. def WithResult(message, result):
  1655. """
  1656. Return a fatal error object that appends the hex values of
  1657. 'result' as a string formatted argument.
  1658. """
  1659. message += " (result was %s)" % hexify(result)
  1660. return FatalError(message)
  1661. class NotImplementedInROMError(FatalError):
  1662. """
  1663. Wrapper class for the error thrown when a particular ESP bootloader function
  1664. is not implemented in the ROM bootloader.
  1665. """
  1666. def __init__(self, bootloader, func):
  1667. FatalError.__init__(self, "%s ROM does not support function %s." % (bootloader.CHIP_NAME, func.__name__))
  1668. class NotSupportedError(FatalError):
  1669. def __init__(self, esp, function_name):
  1670. FatalError.__init__(self, "Function %s is not supported for %s." % (function_name, esp.CHIP_NAME))
  1671. # "Operation" commands, executable at command line. One function each
  1672. #
  1673. # Each function takes either two args (<ESPLoader instance>, <args>) or a single <args>
  1674. # argument.
  1675. def load_ram(esp, args):
  1676. image = LoadFirmwareImage(esp.CHIP_NAME, args.filename)
  1677. print('RAM boot...')
  1678. for seg in image.segments:
  1679. size = len(seg.data)
  1680. print('Downloading %d bytes at %08x...' % (size, seg.addr), end=' ')
  1681. sys.stdout.flush()
  1682. esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, seg.addr)
  1683. seq = 0
  1684. while len(seg.data) > 0:
  1685. esp.mem_block(seg.data[0:esp.ESP_RAM_BLOCK], seq)
  1686. seg.data = seg.data[esp.ESP_RAM_BLOCK:]
  1687. seq += 1
  1688. print('done!')
  1689. print('All segments done, executing at %08x' % image.entrypoint)
  1690. esp.mem_finish(image.entrypoint)
  1691. def read_mem(esp, args):
  1692. print('0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address)))
  1693. def write_mem(esp, args):
  1694. esp.write_reg(args.address, args.value, args.mask, 0)
  1695. print('Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address))
  1696. def dump_mem(esp, args):
  1697. with open(args.filename, 'wb') as f:
  1698. for i in range(args.size // 4):
  1699. d = esp.read_reg(args.address + (i * 4))
  1700. f.write(struct.pack(b'<I', d))
  1701. if f.tell() % 1024 == 0:
  1702. print('\r%d bytes read... (%d %%)' % (f.tell(),
  1703. f.tell() * 100 // args.size),
  1704. end=' ')
  1705. sys.stdout.flush()
  1706. print('Done!')
  1707. def detect_flash_size(esp, args):
  1708. if args.flash_size == 'detect':
  1709. flash_id = esp.flash_id()
  1710. size_id = flash_id >> 16
  1711. args.flash_size = DETECTED_FLASH_SIZES.get(size_id)
  1712. if args.flash_size is None:
  1713. print('Warning: Could not auto-detect Flash size (FlashID=0x%x, SizeID=0x%x), defaulting to 4MB' % (flash_id, size_id))
  1714. args.flash_size = '4MB'
  1715. else:
  1716. print('Auto-detected Flash size:', args.flash_size)
  1717. def _update_image_flash_params(esp, address, args, image):
  1718. """ Modify the flash mode & size bytes if this looks like an executable bootloader image """
  1719. if len(image) < 8:
  1720. return image # not long enough to be a bootloader image
  1721. # unpack the (potential) image header
  1722. magic, _, flash_mode, flash_size_freq = struct.unpack("BBBB", image[:4])
  1723. if address != esp.BOOTLOADER_FLASH_OFFSET or magic != esp.ESP_IMAGE_MAGIC:
  1724. return image # not flashing a bootloader, so don't modify this
  1725. if args.flash_mode != 'keep':
  1726. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1727. flash_freq = flash_size_freq & 0x0F
  1728. if args.flash_freq != 'keep':
  1729. flash_freq = {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1730. flash_size = flash_size_freq & 0xF0
  1731. if args.flash_size != 'keep':
  1732. flash_size = esp.parse_flash_size_arg(args.flash_size)
  1733. flash_params = struct.pack(b'BB', flash_mode, flash_size + flash_freq)
  1734. if flash_params != image[2:4]:
  1735. print('Flash params set to 0x%04x' % struct.unpack(">H", flash_params))
  1736. image = image[0:2] + flash_params + image[4:]
  1737. return image
  1738. def write_flash(esp, args):
  1739. # set args.compress based on default behaviour:
  1740. # -> if either --compress or --no-compress is set, honour that
  1741. # -> otherwise, set --compress unless --no-stub is set
  1742. if args.compress is None and not args.no_compress:
  1743. args.compress = not args.no_stub
  1744. # verify file sizes fit in flash
  1745. flash_end = flash_size_bytes(args.flash_size)
  1746. for address, argfile in args.addr_filename:
  1747. argfile.seek(0,2) # seek to end
  1748. if address + argfile.tell() > flash_end:
  1749. raise FatalError(("File %s (length %d) at offset %d will not fit in %d bytes of flash. " +
  1750. "Use --flash-size argument, or change flashing address.")
  1751. % (argfile.name, argfile.tell(), address, flash_end))
  1752. argfile.seek(0)
  1753. if args.erase_all:
  1754. erase_flash(esp, args)
  1755. for address, argfile in args.addr_filename:
  1756. if args.no_stub:
  1757. print('Erasing flash...')
  1758. image = pad_to(argfile.read(), 4)
  1759. if len(image) == 0:
  1760. print('WARNING: File %s is empty' % argfile.name)
  1761. continue
  1762. image = _update_image_flash_params(esp, address, args, image)
  1763. calcmd5 = hashlib.md5(image).hexdigest()
  1764. uncsize = len(image)
  1765. if args.compress:
  1766. uncimage = image
  1767. image = zlib.compress(uncimage, 9)
  1768. ratio = uncsize / len(image)
  1769. blocks = esp.flash_defl_begin(uncsize, len(image), address)
  1770. else:
  1771. ratio = 1.0
  1772. blocks = esp.flash_begin(uncsize, address)
  1773. argfile.seek(0) # in case we need it again
  1774. seq = 0
  1775. written = 0
  1776. t = time.time()
  1777. while len(image) > 0:
  1778. print('\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) // blocks), end='')
  1779. sys.stdout.flush()
  1780. block = image[0:esp.FLASH_WRITE_SIZE]
  1781. if args.compress:
  1782. esp.flash_defl_block(block, seq, timeout=DEFAULT_TIMEOUT * ratio * 2)
  1783. else:
  1784. # Pad the last block
  1785. block = block + b'\xff' * (esp.FLASH_WRITE_SIZE - len(block))
  1786. esp.flash_block(block, seq)
  1787. image = image[esp.FLASH_WRITE_SIZE:]
  1788. seq += 1
  1789. written += len(block)
  1790. t = time.time() - t
  1791. speed_msg = ""
  1792. if args.compress:
  1793. if t > 0.0:
  1794. speed_msg = " (effective %.1f kbit/s)" % (uncsize / t * 8 / 1000)
  1795. print('\rWrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s...' % (uncsize, written, address, t, speed_msg))
  1796. else:
  1797. if t > 0.0:
  1798. speed_msg = " (%.1f kbit/s)" % (written / t * 8 / 1000)
  1799. print('\rWrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg))
  1800. try:
  1801. res = esp.flash_md5sum(address, uncsize)
  1802. if res != calcmd5:
  1803. print('File md5: %s' % calcmd5)
  1804. print('Flash md5: %s' % res)
  1805. print('MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest()))
  1806. raise FatalError("MD5 of file does not match data in flash!")
  1807. else:
  1808. print('Hash of data verified.')
  1809. except NotImplementedInROMError:
  1810. pass
  1811. print('\nLeaving...')
  1812. if esp.IS_STUB:
  1813. # skip sending flash_finish to ROM loader here,
  1814. # as it causes the loader to exit and run user code
  1815. esp.flash_begin(0, 0)
  1816. if args.compress:
  1817. esp.flash_defl_finish(False)
  1818. else:
  1819. esp.flash_finish(False)
  1820. if args.verify:
  1821. print('Verifying just-written flash...')
  1822. print('(This option is deprecated, flash contents are now always read back after flashing.)')
  1823. verify_flash(esp, args)
  1824. def image_info(args):
  1825. image = LoadFirmwareImage(args.chip, args.filename)
  1826. print('Image version: %d' % image.version)
  1827. print('Entry point: %08x' % image.entrypoint if image.entrypoint != 0 else 'Entry point not set')
  1828. print('%d segments' % len(image.segments))
  1829. print
  1830. idx = 0
  1831. for seg in image.segments:
  1832. idx += 1
  1833. print('Segment %d: %r' % (idx, seg))
  1834. calc_checksum = image.calculate_checksum()
  1835. print('Checksum: %02x (%s)' % (image.checksum,
  1836. 'valid' if image.checksum == calc_checksum else 'invalid - calculated %02x' % calc_checksum))
  1837. try:
  1838. digest_msg = 'Not appended'
  1839. if image.append_digest:
  1840. is_valid = image.stored_digest == image.calc_digest
  1841. digest_msg = "%s (%s)" % (hexify(image.calc_digest).lower(),
  1842. "valid" if is_valid else "invalid")
  1843. print('Validation Hash: %s' % digest_msg)
  1844. except AttributeError:
  1845. pass # ESP8266 image has no append_digest field
  1846. def make_image(args):
  1847. image = ESP8266ROMFirmwareImage()
  1848. if len(args.segfile) == 0:
  1849. raise FatalError('No segments specified')
  1850. if len(args.segfile) != len(args.segaddr):
  1851. raise FatalError('Number of specified files does not match number of specified addresses')
  1852. for (seg, addr) in zip(args.segfile, args.segaddr):
  1853. with open(seg, 'rb') as f:
  1854. data = f.read()
  1855. image.segments.append(ImageSegment(addr, data))
  1856. image.entrypoint = args.entrypoint
  1857. image.save(args.output)
  1858. def elf2image(args):
  1859. e = ELFFile(args.input)
  1860. if args.chip == 'auto': # Default to ESP8266 for backwards compatibility
  1861. print("Creating image for ESP8266...")
  1862. args.chip = 'esp8266'
  1863. if args.chip == 'esp32':
  1864. image = ESP32FirmwareImage()
  1865. image.secure_pad = args.secure_pad
  1866. elif args.version == '1': # ESP8266
  1867. image = ESP8266ROMFirmwareImage()
  1868. else:
  1869. image = ESP8266V2FirmwareImage()
  1870. image.entrypoint = e.entrypoint
  1871. image.segments = e.sections # ELFSection is a subclass of ImageSegment
  1872. image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1873. image.flash_size_freq = image.ROM_LOADER.FLASH_SIZES[args.flash_size]
  1874. image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1875. if args.elf_sha256_offset:
  1876. image.elf_sha256 = e.sha256()
  1877. image.elf_sha256_offset = args.elf_sha256_offset
  1878. image.verify()
  1879. if args.output is None:
  1880. args.output = image.default_output_name(args.input)
  1881. image.save(args.output)
  1882. def read_mac(esp, args):
  1883. mac = esp.read_mac()
  1884. def print_mac(label, mac):
  1885. print('%s: %s' % (label, ':'.join(map(lambda x: '%02x' % x, mac))))
  1886. print_mac("MAC", mac)
  1887. def chip_id(esp, args):
  1888. try:
  1889. chipid = esp.chip_id()
  1890. print('Chip ID: 0x%08x' % chipid)
  1891. except NotSupportedError:
  1892. print('Warning: %s has no Chip ID. Reading MAC instead.' % esp.CHIP_NAME)
  1893. read_mac(esp, args)
  1894. def erase_flash(esp, args):
  1895. print('Erasing flash (this may take a while)...')
  1896. t = time.time()
  1897. esp.erase_flash()
  1898. print('Chip erase completed successfully in %.1fs' % (time.time() - t))
  1899. def erase_region(esp, args):
  1900. print('Erasing region (may be slow depending on size)...')
  1901. t = time.time()
  1902. esp.erase_region(args.address, args.size)
  1903. print('Erase completed successfully in %.1f seconds.' % (time.time() - t))
  1904. def run(esp, args):
  1905. esp.run()
  1906. def flash_id(esp, args):
  1907. flash_id = esp.flash_id()
  1908. print('Manufacturer: %02x' % (flash_id & 0xff))
  1909. flid_lowbyte = (flash_id >> 16) & 0xFF
  1910. print('Device: %02x%02x' % ((flash_id >> 8) & 0xff, flid_lowbyte))
  1911. print('Detected flash size: %s' % (DETECTED_FLASH_SIZES.get(flid_lowbyte, "Unknown")))
  1912. def read_flash(esp, args):
  1913. if args.no_progress:
  1914. flash_progress = None
  1915. else:
  1916. def flash_progress(progress, length):
  1917. msg = '%d (%d %%)' % (progress, progress * 100.0 / length)
  1918. padding = '\b' * len(msg)
  1919. if progress == length:
  1920. padding = '\n'
  1921. sys.stdout.write(msg + padding)
  1922. sys.stdout.flush()
  1923. t = time.time()
  1924. data = esp.read_flash(args.address, args.size, flash_progress)
  1925. t = time.time() - t
  1926. print('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  1927. % (len(data), args.address, t, len(data) / t * 8 / 1000))
  1928. with open(args.filename, 'wb') as f:
  1929. f.write(data)
  1930. def verify_flash(esp, args):
  1931. differences = False
  1932. for address, argfile in args.addr_filename:
  1933. image = pad_to(argfile.read(), 4)
  1934. argfile.seek(0) # rewind in case we need it again
  1935. image = _update_image_flash_params(esp, address, args, image)
  1936. image_size = len(image)
  1937. print('Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name))
  1938. # Try digest first, only read if there are differences.
  1939. digest = esp.flash_md5sum(address, image_size)
  1940. expected_digest = hashlib.md5(image).hexdigest()
  1941. if digest == expected_digest:
  1942. print('-- verify OK (digest matched)')
  1943. continue
  1944. else:
  1945. differences = True
  1946. if getattr(args, 'diff', 'no') != 'yes':
  1947. print('-- verify FAILED (digest mismatch)')
  1948. continue
  1949. flash = esp.read_flash(address, image_size)
  1950. assert flash != image
  1951. diff = [i for i in range(image_size) if flash[i] != image[i]]
  1952. print('-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0]))
  1953. for d in diff:
  1954. flash_byte = flash[d]
  1955. image_byte = image[d]
  1956. if PYTHON2:
  1957. flash_byte = ord(flash_byte)
  1958. image_byte = ord(image_byte)
  1959. print(' %08x %02x %02x' % (address + d, flash_byte, image_byte))
  1960. if differences:
  1961. raise FatalError("Verify failed.")
  1962. def read_flash_status(esp, args):
  1963. print('Status value: 0x%04x' % esp.read_status(args.bytes))
  1964. def write_flash_status(esp, args):
  1965. fmt = "0x%%0%dx" % (args.bytes * 2)
  1966. args.value = args.value & ((1 << (args.bytes * 8)) - 1)
  1967. print(('Initial flash status: ' + fmt) % esp.read_status(args.bytes))
  1968. print(('Setting flash status: ' + fmt) % args.value)
  1969. esp.write_status(args.value, args.bytes, args.non_volatile)
  1970. print(('After flash status: ' + fmt) % esp.read_status(args.bytes))
  1971. def version(args):
  1972. print(__version__)
  1973. #
  1974. # End of operations functions
  1975. #
  1976. def main(custom_commandline=None):
  1977. """
  1978. Main function for esptool
  1979. custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
  1980. as strings.
  1981. """
  1982. parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
  1983. parser.add_argument('--chip', '-c',
  1984. help='Target chip type',
  1985. choices=['auto', 'esp8266', 'esp32'],
  1986. default=os.environ.get('ESPTOOL_CHIP', 'auto'))
  1987. parser.add_argument(
  1988. '--port', '-p',
  1989. help='Serial port device',
  1990. default=os.environ.get('ESPTOOL_PORT', None))
  1991. parser.add_argument(
  1992. '--baud', '-b',
  1993. help='Serial port baud rate used when flashing/reading',
  1994. type=arg_auto_int,
  1995. default=os.environ.get('ESPTOOL_BAUD', ESPLoader.ESP_ROM_BAUD))
  1996. parser.add_argument(
  1997. '--before',
  1998. help='What to do before connecting to the chip',
  1999. choices=['default_reset', 'no_reset', 'no_reset_no_sync'],
  2000. default=os.environ.get('ESPTOOL_BEFORE', 'default_reset'))
  2001. parser.add_argument(
  2002. '--after', '-a',
  2003. help='What to do after esptool.py is finished',
  2004. choices=['hard_reset', 'soft_reset', 'no_reset'],
  2005. default=os.environ.get('ESPTOOL_AFTER', 'hard_reset'))
  2006. parser.add_argument(
  2007. '--no-stub',
  2008. help="Disable launching the flasher stub, only talk to ROM bootloader. Some features will not be available.",
  2009. action='store_true')
  2010. parser.add_argument(
  2011. '--trace', '-t',
  2012. help="Enable trace-level output of esptool.py interactions.",
  2013. action='store_true')
  2014. parser.add_argument(
  2015. '--override-vddsdio',
  2016. help="Override ESP32 VDDSDIO internal voltage regulator (use with care)",
  2017. choices=ESP32ROM.OVERRIDE_VDDSDIO_CHOICES,
  2018. nargs='?')
  2019. subparsers = parser.add_subparsers(
  2020. dest='operation',
  2021. help='Run esptool {command} -h for additional help')
  2022. def add_spi_connection_arg(parent):
  2023. parent.add_argument('--spi-connection', '-sc', help='ESP32-only argument. Override default SPI Flash connection. ' +
  2024. '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).',
  2025. action=SpiConnectionAction)
  2026. parser_load_ram = subparsers.add_parser(
  2027. 'load_ram',
  2028. help='Download an image to RAM and execute')
  2029. parser_load_ram.add_argument('filename', help='Firmware image')
  2030. parser_dump_mem = subparsers.add_parser(
  2031. 'dump_mem',
  2032. help='Dump arbitrary memory to disk')
  2033. parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
  2034. parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  2035. parser_dump_mem.add_argument('filename', help='Name of binary dump')
  2036. parser_read_mem = subparsers.add_parser(
  2037. 'read_mem',
  2038. help='Read arbitrary memory location')
  2039. parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
  2040. parser_write_mem = subparsers.add_parser(
  2041. 'write_mem',
  2042. help='Read-modify-write to arbitrary memory location')
  2043. parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
  2044. parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
  2045. parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int)
  2046. def add_spi_flash_subparsers(parent, is_elf2image):
  2047. """ Add common parser arguments for SPI flash properties """
  2048. extra_keep_args = [] if is_elf2image else ['keep']
  2049. auto_detect = not is_elf2image
  2050. parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
  2051. choices=extra_keep_args + ['40m', '26m', '20m', '80m'],
  2052. default=os.environ.get('ESPTOOL_FF', '40m' if is_elf2image else 'keep'))
  2053. parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
  2054. choices=extra_keep_args + ['qio', 'qout', 'dio', 'dout'],
  2055. default=os.environ.get('ESPTOOL_FM', 'qio' if is_elf2image else 'keep'))
  2056. parent.add_argument('--flash_size', '-fs', help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16M)'
  2057. ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1)',
  2058. action=FlashSizeAction, auto_detect=auto_detect,
  2059. default=os.environ.get('ESPTOOL_FS', 'detect' if auto_detect else '1MB'))
  2060. add_spi_connection_arg(parent)
  2061. parser_write_flash = subparsers.add_parser('write_flash', help='Write a binary blob to flash')
  2062. parser_write_flash.add_argument('addr_filename', metavar='<address> <filename>', help='Address followed by binary filename, separated by space',
  2063. action=AddrFilenamePairAction)
  2064. parser_write_flash.add_argument('--erase-all', '-e',
  2065. help='Erase all regions of flash (not just write areas) before programming',
  2066. action="store_true")
  2067. add_spi_flash_subparsers(parser_write_flash, is_elf2image=False)
  2068. parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  2069. parser_write_flash.add_argument('--verify', help='Verify just-written data on flash ' +
  2070. '(mostly superfluous, data is read back during flashing)', action='store_true')
  2071. compress_args = parser_write_flash.add_mutually_exclusive_group(required=False)
  2072. compress_args.add_argument('--compress', '-z', help='Compress data in transfer (default unless --no-stub is specified)',action="store_true", default=None)
  2073. compress_args.add_argument('--no-compress', '-u', help='Disable data compression during transfer (default if --no-stub is specified)',action="store_true")
  2074. subparsers.add_parser(
  2075. 'run',
  2076. help='Run application code in flash')
  2077. parser_image_info = subparsers.add_parser(
  2078. 'image_info',
  2079. help='Dump headers from an application image')
  2080. parser_image_info.add_argument('filename', help='Image file to parse')
  2081. parser_make_image = subparsers.add_parser(
  2082. 'make_image',
  2083. help='Create an application image from binary files')
  2084. parser_make_image.add_argument('output', help='Output image file')
  2085. parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
  2086. parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
  2087. parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
  2088. parser_elf2image = subparsers.add_parser(
  2089. 'elf2image',
  2090. help='Create an application image from ELF file')
  2091. parser_elf2image.add_argument('input', help='Input ELF file')
  2092. parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
  2093. parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1')
  2094. parser_elf2image.add_argument('--secure-pad', action='store_true', help='Pad image so once signed it will end on a 64KB boundary. For ESP32 images only.')
  2095. 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.',
  2096. type=arg_auto_int, default=None)
  2097. add_spi_flash_subparsers(parser_elf2image, is_elf2image=True)
  2098. subparsers.add_parser(
  2099. 'read_mac',
  2100. help='Read MAC address from OTP ROM')
  2101. subparsers.add_parser(
  2102. 'chip_id',
  2103. help='Read Chip ID from OTP ROM')
  2104. parser_flash_id = subparsers.add_parser(
  2105. 'flash_id',
  2106. help='Read SPI flash manufacturer and device ID')
  2107. add_spi_connection_arg(parser_flash_id)
  2108. parser_read_status = subparsers.add_parser(
  2109. 'read_flash_status',
  2110. help='Read SPI flash status register')
  2111. add_spi_connection_arg(parser_read_status)
  2112. parser_read_status.add_argument('--bytes', help='Number of bytes to read (1-3)', type=int, choices=[1,2,3], default=2)
  2113. parser_write_status = subparsers.add_parser(
  2114. 'write_flash_status',
  2115. help='Write SPI flash status register')
  2116. add_spi_connection_arg(parser_write_status)
  2117. parser_write_status.add_argument('--non-volatile', help='Write non-volatile bits (use with caution)', action='store_true')
  2118. parser_write_status.add_argument('--bytes', help='Number of status bytes to write (1-3)', type=int, choices=[1,2,3], default=2)
  2119. parser_write_status.add_argument('value', help='New value', type=arg_auto_int)
  2120. parser_read_flash = subparsers.add_parser(
  2121. 'read_flash',
  2122. help='Read SPI flash content')
  2123. add_spi_connection_arg(parser_read_flash)
  2124. parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
  2125. parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  2126. parser_read_flash.add_argument('filename', help='Name of binary dump')
  2127. parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  2128. parser_verify_flash = subparsers.add_parser(
  2129. 'verify_flash',
  2130. help='Verify a binary blob against flash')
  2131. parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
  2132. action=AddrFilenamePairAction)
  2133. parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
  2134. choices=['no', 'yes'], default='no')
  2135. add_spi_flash_subparsers(parser_verify_flash, is_elf2image=False)
  2136. parser_erase_flash = subparsers.add_parser(
  2137. 'erase_flash',
  2138. help='Perform Chip Erase on SPI flash')
  2139. add_spi_connection_arg(parser_erase_flash)
  2140. parser_erase_region = subparsers.add_parser(
  2141. 'erase_region',
  2142. help='Erase a region of the flash')
  2143. add_spi_connection_arg(parser_erase_region)
  2144. parser_erase_region.add_argument('address', help='Start address (must be multiple of 4096)', type=arg_auto_int)
  2145. parser_erase_region.add_argument('size', help='Size of region to erase (must be multiple of 4096)', type=arg_auto_int)
  2146. subparsers.add_parser(
  2147. 'version', help='Print esptool version')
  2148. # internal sanity check - every operation matches a module function of the same name
  2149. for operation in subparsers.choices.keys():
  2150. assert operation in globals(), "%s should be a module function" % operation
  2151. expand_file_arguments()
  2152. args = parser.parse_args(custom_commandline)
  2153. print('esptool.py v%s' % __version__)
  2154. # operation function can take 1 arg (args), 2 args (esp, arg)
  2155. # or be a member function of the ESPLoader class.
  2156. if args.operation is None:
  2157. parser.print_help()
  2158. sys.exit(1)
  2159. operation_func = globals()[args.operation]
  2160. if PYTHON2:
  2161. # This function is depreciated in Python3
  2162. operation_args = inspect.getargspec(operation_func).args
  2163. else:
  2164. operation_args = inspect.getfullargspec(operation_func).args
  2165. if operation_args[0] == 'esp': # operation function takes an ESPLoader connection object
  2166. if args.before != "no_reset_no_sync":
  2167. initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
  2168. else:
  2169. initial_baud = args.baud
  2170. if args.port is None:
  2171. ser_list = sorted(ports.device for ports in list_ports.comports())
  2172. print("Found %d serial ports" % len(ser_list))
  2173. else:
  2174. ser_list = [args.port]
  2175. esp = None
  2176. for each_port in reversed(ser_list):
  2177. print("Serial port %s" % each_port)
  2178. try:
  2179. if args.chip == 'auto':
  2180. esp = ESPLoader.detect_chip(each_port, initial_baud, args.before, args.trace)
  2181. else:
  2182. chip_class = {
  2183. 'esp8266': ESP8266ROM,
  2184. 'esp32': ESP32ROM,
  2185. }[args.chip]
  2186. esp = chip_class(each_port, initial_baud, args.trace)
  2187. esp.connect(args.before)
  2188. break
  2189. except (FatalError, OSError) as err:
  2190. if args.port is not None:
  2191. raise
  2192. print("%s failed to connect: %s" % (each_port, err))
  2193. esp = None
  2194. if esp is None:
  2195. raise FatalError("All of the %d available serial ports could not connect to a Espressif device." % len(ser_list))
  2196. print("Chip is %s" % (esp.get_chip_description()))
  2197. print("Features: %s" % ", ".join(esp.get_chip_features()))
  2198. read_mac(esp, args)
  2199. if not args.no_stub:
  2200. esp = esp.run_stub()
  2201. if args.override_vddsdio:
  2202. esp.override_vddsdio(args.override_vddsdio)
  2203. if args.baud > initial_baud:
  2204. try:
  2205. esp.change_baud(args.baud)
  2206. except NotImplementedInROMError:
  2207. print("WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d" % initial_baud)
  2208. # override common SPI flash parameter stuff if configured to do so
  2209. if hasattr(args, "spi_connection") and args.spi_connection is not None:
  2210. if esp.CHIP_NAME != "ESP32":
  2211. raise FatalError("Chip %s does not support --spi-connection option." % esp.CHIP_NAME)
  2212. print("Configuring SPI flash mode...")
  2213. esp.flash_spi_attach(args.spi_connection)
  2214. elif args.no_stub:
  2215. print("Enabling default SPI flash mode...")
  2216. # ROM loader doesn't enable flash unless we explicitly do it
  2217. esp.flash_spi_attach(0)
  2218. if hasattr(args, "flash_size"):
  2219. print("Configuring flash size...")
  2220. detect_flash_size(esp, args)
  2221. esp.flash_set_parameters(flash_size_bytes(args.flash_size))
  2222. try:
  2223. operation_func(esp, args)
  2224. finally:
  2225. try: # Clean up AddrFilenamePairAction files
  2226. for address, argfile in args.addr_filename:
  2227. argfile.close()
  2228. except AttributeError:
  2229. pass
  2230. # Handle post-operation behaviour (reset or other)
  2231. if operation_func == load_ram:
  2232. # the ESP is now running the loaded image, so let it run
  2233. print('Exiting immediately.')
  2234. elif args.after == 'hard_reset':
  2235. print('Hard resetting via RTS pin...')
  2236. esp.hard_reset()
  2237. elif args.after == 'soft_reset':
  2238. print('Soft resetting...')
  2239. # flash_finish will trigger a soft reset
  2240. esp.soft_reset(False)
  2241. else:
  2242. print('Staying in bootloader.')
  2243. if esp.IS_STUB:
  2244. esp.soft_reset(True) # exit stub back to ROM loader
  2245. esp._port.close()
  2246. else:
  2247. operation_func(args)
  2248. def expand_file_arguments():
  2249. """ Any argument starting with "@" gets replaced with all values read from a text file.
  2250. Text file arguments can be split by newline or by space.
  2251. Values are added "as-is", as if they were specified in this order on the command line.
  2252. """
  2253. new_args = []
  2254. expanded = False
  2255. for arg in sys.argv:
  2256. if arg.startswith("@"):
  2257. expanded = True
  2258. with open(arg[1:],"r") as f:
  2259. for line in f.readlines():
  2260. new_args += shlex.split(line)
  2261. else:
  2262. new_args.append(arg)
  2263. if expanded:
  2264. print("esptool.py %s" % (" ".join(new_args[1:])))
  2265. sys.argv = new_args
  2266. class FlashSizeAction(argparse.Action):
  2267. """ Custom flash size parser class to support backwards compatibility with megabit size arguments.
  2268. (At next major relase, remove deprecated sizes and this can become a 'normal' choices= argument again.)
  2269. """
  2270. def __init__(self, option_strings, dest, nargs=1, auto_detect=False, **kwargs):
  2271. super(FlashSizeAction, self).__init__(option_strings, dest, nargs, **kwargs)
  2272. self._auto_detect = auto_detect
  2273. def __call__(self, parser, namespace, values, option_string=None):
  2274. try:
  2275. value = {
  2276. '2m': '256KB',
  2277. '4m': '512KB',
  2278. '8m': '1MB',
  2279. '16m': '2MB',
  2280. '32m': '4MB',
  2281. '16m-c1': '2MB-c1',
  2282. '32m-c1': '4MB-c1',
  2283. }[values[0]]
  2284. print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
  2285. print("Please use the equivalent size '%s'." % (value))
  2286. print("Megabit arguments may be removed in a future release.")
  2287. except KeyError:
  2288. value = values[0]
  2289. known_sizes = dict(ESP8266ROM.FLASH_SIZES)
  2290. known_sizes.update(ESP32ROM.FLASH_SIZES)
  2291. if self._auto_detect:
  2292. known_sizes['detect'] = 'detect'
  2293. if value not in known_sizes:
  2294. raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
  2295. setattr(namespace, self.dest, value)
  2296. class SpiConnectionAction(argparse.Action):
  2297. """ Custom action to parse 'spi connection' override. Values are SPI, HSPI, or a sequence of 5 pin numbers separated by commas.
  2298. """
  2299. def __call__(self, parser, namespace, value, option_string=None):
  2300. if value.upper() == "SPI":
  2301. value = 0
  2302. elif value.upper() == "HSPI":
  2303. value = 1
  2304. elif "," in value:
  2305. values = value.split(",")
  2306. if len(values) != 5:
  2307. 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)
  2308. try:
  2309. values = tuple(int(v,0) for v in values)
  2310. except ValueError:
  2311. raise argparse.ArgumentError(self, '%s is not a valid argument. All pins must be numeric values' % values)
  2312. if any([v for v in values if v > 33 or v < 0]):
  2313. raise argparse.ArgumentError(self, 'Pin numbers must be in the range 0-33.')
  2314. # encode the pin numbers as a 32-bit integer with packed 6-bit values, the same way ESP32 ROM takes them
  2315. # TODO: make this less ESP32 ROM specific somehow...
  2316. clk,q,d,hd,cs = values
  2317. value = (hd << 24) | (cs << 18) | (d << 12) | (q << 6) | clk
  2318. else:
  2319. raise argparse.ArgumentError(self, '%s is not a valid spi-connection value. ' +
  2320. 'Values are SPI, HSPI, or a sequence of 5 pin numbers CLK,Q,D,HD,CS).' % value)
  2321. setattr(namespace, self.dest, value)
  2322. class AddrFilenamePairAction(argparse.Action):
  2323. """ Custom parser class for the address/filename pairs passed as arguments """
  2324. def __init__(self, option_strings, dest, nargs='+', **kwargs):
  2325. super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
  2326. def __call__(self, parser, namespace, values, option_string=None):
  2327. # validate pair arguments
  2328. pairs = []
  2329. for i in range(0,len(values),2):
  2330. try:
  2331. address = int(values[i],0)
  2332. except ValueError:
  2333. raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
  2334. try:
  2335. argfile = open(values[i + 1], 'rb')
  2336. except IOError as e:
  2337. raise argparse.ArgumentError(self, e)
  2338. except IndexError:
  2339. raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
  2340. pairs.append((address, argfile))
  2341. # Sort the addresses and check for overlapping
  2342. end = 0
  2343. for address, argfile in sorted(pairs):
  2344. argfile.seek(0,2) # seek to end
  2345. size = argfile.tell()
  2346. argfile.seek(0)
  2347. sector_start = address & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)
  2348. sector_end = ((address + size + ESPLoader.FLASH_SECTOR_SIZE - 1) & ~(ESPLoader.FLASH_SECTOR_SIZE - 1)) - 1
  2349. if sector_start < end:
  2350. message = 'Detected overlap at address: 0x%x for file: %s' % (address, argfile.name)
  2351. raise argparse.ArgumentError(self, message)
  2352. end = sector_end
  2353. setattr(namespace, self.dest, pairs)
  2354. # Binary stub code (see flasher_stub dir for source & details)
  2355. ESP8266ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  2356. eNrNPXt/00a2X8WSQ0iCoRpJ1iMNxXaCeRS2ATYBdtNtpJEE5ZZuYvzbUJZ+96vzmhnJDoG+7v0j1CNpZs6c9zlzZvrf68v6/fL67qC8fvK+yE7eq+DkfRBM2n/Uyfumgb/5HB51/7L2r6nvfHd/+qDtF7d/JXx6\
  2357. p32ruVHfoc8yp1vTftnkMMuEvqQXp70J1Prfyh2poT8DkO7ORDP0oLadJmuXc/I+1zd4HUUgv9pprzsDxw7UZkCGpIOJXkOGKzvY6iBosO3A2hIjqxCsFw6AQCPTO4dG7TRyg/jYeQOdVWmHLoKTRQ85mQHhZCk/\
  2358. D9t/aqehQmcI7YBRBk5DNWYRe+3jnAEKXFCBWEXlQBc40AWdl5rmMvOosYMi1eWBIHBYDxsye6mFRi3hs8xpFLbxAntNDpDdJ6NH+J/ga/zP+/uGax7yrzJ+wL+0vsW/VDtPHXKjynL89do8awepZOK8ha9G5p48\
  2359. 2hTIeEivHb2kteVtz0IR70MX1f7WgV8MfaQjrTss9tunYTFrxw+LKcxXtMM1YXGHJKhOaDRtMAVTIPraf8qQ8QhYiuc9AQwApvBbP4WvMp420zsedIB5W4qUEXTyhHDtQyUsoeThzgjmH9CoGlATypSylj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RQ2r48GeGnxD++WxQKuLlZBGmdxmsZx+6b+ebn4xX2YtQ+rYlnIHccmR4E6ZOxsmTkbAlRwwn+IiuccEeA1rdppVKHTwBx3yg081CtvIGjkN3t8FgM7\
  2419. hE6j0wFSKLW5Kjmm+A4bKI/Fuj5O4weasv94j9gcH0N9c41HvibfmV+Xj0je7/rPMF8lty6jwlTUWFJIRZgqnQZeBRpfOeXljZoPDq++wajboDEl/6VtfG8ocMPpCsd6DJ5xi0PIUSjzJnVHDL4c2N/ZGBpAXppf\
  2420. U2cNKzsn/ax0/5ad3jna7glLt2KI6s46rd7V0ao3Nx4gc+1n4F6jaxudGwmLXjqnN6ZWay4IV73v+5eGh7121GvHvXbSa2e9tu62VQ8e1fl+4DY6X7o3j6vT1R2vP+1PXdEOv5CHruKpq3is306uaKdXtLNPtpef\
  2421. aP38iVb3avJ1bf3J9uJTsnPl35fKbfJFOFp+wbr7kDdXaIEe5KoHiephUXXGG7qNG26jM2znYNu+23jmNjoEedfTND04i15b99p1tEZK1F8oxX+2Fvi9WuL3apHfq2V+rxa6qv2FfyqwyTQjgSlKHp01HbOkxWYL\
  2422. ZcFY47yGkTR1+f8YY3Wl19nrdZ3kKA3bkDP79X8BZBZfEg==\
  2423. """)))
  2424. ESP32ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  2425. eNqNWnt31LgV/yqOYfJaskeyPbZEz0IS6BBg2xIoIdDp2bFlOyFbcoDOQjgL/ezVfVnyzNDtHxNkPa/u43cf4vedZXez3LmbNDvzm94k/k9xH1oKW+XR/Eb5ptX+s/W/fn7jVEKdxsyX/i+01O2zExrFmfX/M1PD\
  2426. foomyE8roUBFrehnhKJu6ocd7WTgzIbayvepbDh7D9bEVG2tkZe+pR35c3e+PPu4Tj9uA5vrTG7iv4tkV22+iVKHRGoX6NSlp6QONHdtxDO3cqa1dGboQCLOvnyfe8NPh7ZRYbUDofb3aQP5KbpHJO4toSZLYQjo\
  2427. fuAbU7iJCTfpahqtp8L982Ni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453. y7+X9Uf4H2taVUVuc2WMH+mulx+/DJ1FUUJnWy9r/q9tUcF5h0fijfIqL0udffsvV73qkg==\
  2454. """)))
  2455. def _main():
  2456. try:
  2457. main()
  2458. except FatalError as e:
  2459. print('\nA fatal error occurred: %s' % e)
  2460. sys.exit(2)
  2461. if __name__ == '__main__':
  2462. _main()