esptool.py 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  1. #!/usr/bin/env python
  2. # NB: Before sending a PR to change the above line to '#!/usr/bin/env python2', please read https://github.com/espressif/esptool/issues/21
  3. #
  4. # ESP8266 & ESP32 ROM Bootloader Utility
  5. # Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, Espressif Systems (Shanghai) PTE LTD, other contributors as noted.
  6. # https://github.com/espressif/esptool
  7. #
  8. # This program is free software; you can redistribute it and/or modify it under
  9. # the terms of the GNU General Public License as published by the Free Software
  10. # Foundation; either version 2 of the License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful, but WITHOUT
  13. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along with
  17. # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  18. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. import argparse
  20. import hashlib
  21. import inspect
  22. import os
  23. import serial
  24. import struct
  25. import sys
  26. import time
  27. import base64
  28. import zlib
  29. import shlex
  30. __version__ = "2.0-FHEM"
  31. MAX_UINT32 = 0xffffffff
  32. MAX_UINT24 = 0xffffff
  33. def check_supported_function(func, check_func):
  34. """
  35. Decorator implementation that wraps a check around an ESPLoader
  36. bootloader function to check if it's supported.
  37. This is used to capture the multidimensional differences in
  38. functionality between the ESP8266 & ESP32 ROM loaders, and the
  39. software stub that runs on both. Not possible to do this cleanly
  40. via inheritance alone.
  41. """
  42. def inner(*args, **kwargs):
  43. obj = args[0]
  44. if check_func(obj):
  45. return func(*args, **kwargs)
  46. else:
  47. raise NotImplementedInROMError(obj, func)
  48. return inner
  49. def stub_function_only(func):
  50. """ Attribute for a function only supported in the software stub loader """
  51. return check_supported_function(func, lambda o: o.IS_STUB)
  52. def stub_and_esp32_function_only(func):
  53. """ Attribute for a function only supported by software stubs or ESP32 ROM """
  54. return check_supported_function(func, lambda o: o.IS_STUB or o.CHIP_NAME == "ESP32")
  55. def esp8266_function_only(func):
  56. """ Attribute for a function only supported on ESP8266 """
  57. return check_supported_function(func, lambda o: o.CHIP_NAME == "ESP8266")
  58. class ESPLoader(object):
  59. """ Base class providing access to ESP ROM & softtware stub bootloaders.
  60. Subclasses provide ESP8266 & ESP32 specific functionality.
  61. Don't instantiate this base class directly, either instantiate a subclass or
  62. call ESPLoader.detect_chip() which will interrogate the chip and return the
  63. appropriate subclass instance.
  64. """
  65. CHIP_NAME = "Espressif device"
  66. IS_STUB = False
  67. DEFAULT_PORT = "/dev/ttyUSB0"
  68. # Commands supported by ESP8266 ROM bootloader
  69. ESP_FLASH_BEGIN = 0x02
  70. ESP_FLASH_DATA = 0x03
  71. ESP_FLASH_END = 0x04
  72. ESP_MEM_BEGIN = 0x05
  73. ESP_MEM_END = 0x06
  74. ESP_MEM_DATA = 0x07
  75. ESP_SYNC = 0x08
  76. ESP_WRITE_REG = 0x09
  77. ESP_READ_REG = 0x0a
  78. # Some comands supported by ESP32 ROM bootloader (or -8266 w/ stub)
  79. ESP_SPI_SET_PARAMS = 0x0B
  80. ESP_SPI_ATTACH = 0x0D
  81. ESP_CHANGE_BAUDRATE = 0x0F
  82. ESP_FLASH_DEFL_BEGIN = 0x10
  83. ESP_FLASH_DEFL_DATA = 0x11
  84. ESP_FLASH_DEFL_END = 0x12
  85. ESP_SPI_FLASH_MD5 = 0x13
  86. # Some commands supported by stub only
  87. ESP_ERASE_FLASH = 0xD0
  88. ESP_ERASE_REGION = 0xD1
  89. ESP_READ_FLASH = 0xD2
  90. ESP_RUN_USER_CODE = 0xD3
  91. # Maximum block sized for RAM and Flash writes, respectively.
  92. ESP_RAM_BLOCK = 0x1800
  93. FLASH_WRITE_SIZE = 0x400
  94. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  95. ESP_ROM_BAUD = 115200
  96. # First byte of the application image
  97. ESP_IMAGE_MAGIC = 0xe9
  98. # Initial state for the checksum routine
  99. ESP_CHECKSUM_MAGIC = 0xef
  100. # Flash sector size, minimum unit of erase.
  101. FLASH_SECTOR_SIZE = 0x1000
  102. UART_DATA_REG_ADDR = 0x60000078
  103. # Memory addresses
  104. IROM_MAP_START = 0x40200000
  105. IROM_MAP_END = 0x40300000
  106. # The number of bytes in the UART response that signify command status
  107. STATUS_BYTES_LENGTH = 2
  108. def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD):
  109. """Base constructor for ESPLoader bootloader interaction
  110. Don't call this constructor, either instantiate ESP8266ROM
  111. or ESP32ROM, or use ESPLoader.detect_chip().
  112. This base class has all of the instance methods for bootloader
  113. functionality supported across various chips & stub
  114. loaders. Subclasses replace the functions they don't support
  115. with ones which throw NotImplementedInROMError().
  116. """
  117. if isinstance(port, serial.Serial):
  118. self._port = port
  119. else:
  120. self._port = serial.serial_for_url(port)
  121. self._slip_reader = slip_reader(self._port)
  122. # setting baud rate in a separate step is a workaround for
  123. # CH341 driver on some Linux versions (this opens at 9600 then
  124. # sets), shouldn't matter for other platforms/drivers. See
  125. # https://github.com/espressif/esptool/issues/44#issuecomment-107094446
  126. self._port.baudrate = baud
  127. @staticmethod
  128. def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset'):
  129. """ Use serial access to detect the chip type.
  130. We use the UART's datecode register for this, it's mapped at
  131. the same address on ESP8266 & ESP32 so we can use one
  132. memory read and compare to the datecode register for each chip
  133. type.
  134. This routine automatically performs ESPLoader.connect() (passing
  135. connect_mode parameter) as part of querying the chip.
  136. """
  137. detect_port = ESPLoader(port, baud)
  138. detect_port.connect(connect_mode)
  139. sys.stdout.write('Detecting chip type... ')
  140. date_reg = detect_port.read_reg(ESPLoader.UART_DATA_REG_ADDR)
  141. for cls in [ESP8266ROM, ESP32ROM]:
  142. if date_reg == cls.DATE_REG_VALUE:
  143. # don't connect a second time
  144. inst = cls(detect_port._port, baud)
  145. print '%s' % inst.CHIP_NAME
  146. return inst
  147. print ''
  148. raise FatalError("Unexpected UART datecode value 0x%08x. Failed to autodetect chip type." % date_reg)
  149. """ Read a SLIP packet from the serial port """
  150. def read(self):
  151. r = self._slip_reader.next()
  152. return r
  153. """ Write bytes to the serial port while performing SLIP escaping """
  154. def write(self, packet):
  155. buf = '\xc0' \
  156. + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \
  157. + '\xc0'
  158. self._port.write(buf)
  159. """ Calculate checksum of a blob, as it is defined by the ROM """
  160. @staticmethod
  161. def checksum(data, state=ESP_CHECKSUM_MAGIC):
  162. for b in data:
  163. state ^= ord(b)
  164. return state
  165. """ Send a request and read the response """
  166. def command(self, op=None, data="", chk=0, wait_response=True):
  167. if op is not None:
  168. pkt = struct.pack('<BBHI', 0x00, op, len(data), chk) + data
  169. self.write(pkt)
  170. if not wait_response:
  171. return
  172. # tries to get a response until that response has the
  173. # same operation as the request or a retries limit has
  174. # exceeded. This is needed for some esp8266s that
  175. # reply with more sync responses than expected.
  176. for retry in xrange(100):
  177. p = self.read()
  178. if len(p) < 8:
  179. continue
  180. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
  181. if resp != 1:
  182. continue
  183. data = p[8:]
  184. if op is None or op_ret == op:
  185. return val, data
  186. raise FatalError("Response doesn't match request")
  187. def check_command(self, op_description, op=None, data="", chk=0):
  188. """
  189. Execute a command with 'command', check the result code and throw an appropriate
  190. FatalError if it fails.
  191. Returns the "result" of a successful command.
  192. """
  193. val, data = self.command(op, data, chk)
  194. # things are a bit weird here, bear with us
  195. # the status bytes are the last 2/4 bytes in the data (depending on chip)
  196. if len(data) < self.STATUS_BYTES_LENGTH:
  197. raise FatalError("Failed to %s. Only got %d byte status response." % (op_description, len(data)))
  198. status_bytes = data[-self.STATUS_BYTES_LENGTH:]
  199. # we only care if the first one is non-zero. If it is, the second byte is a reason.
  200. if status_bytes[0] != '\0':
  201. raise FatalError.WithResult('Failed to %s' % op_description, status_bytes)
  202. # if we had more data than just the status bytes, return it as the result
  203. # (this is used by the md5sum command, maybe other commands?)
  204. if len(data) > self.STATUS_BYTES_LENGTH:
  205. return data[:-self.STATUS_BYTES_LENGTH]
  206. else: # otherwise, just return the 'val' field which comes from the reply header (this is used by read_reg)
  207. return val
  208. def flush_input(self):
  209. self._port.flushInput()
  210. self._slip_reader = slip_reader(self._port)
  211. def sync(self):
  212. """ Perform a connection test """
  213. self.command(self.ESP_SYNC, '\x07\x07\x12\x20' + 32 * '\x55')
  214. for i in xrange(7):
  215. self.command()
  216. def connect(self, mode='default_reset'):
  217. """ Try connecting repeatedly until successful, or giving up """
  218. print 'Connecting...'
  219. for _ in xrange(10):
  220. # issue reset-to-bootloader:
  221. # RTS = either CH_PD/EN or nRESET (both active low = chip in reset
  222. # DTR = GPIO0 (active low = boot to flasher)
  223. #
  224. # DTR & RTS are active low signals,
  225. # ie True = pin @ 0V, False = pin @ VCC.
  226. if mode != 'no_reset':
  227. self._port.setDTR(False) # IO0=HIGH
  228. self._port.setRTS(True) # EN=LOW, chip in reset
  229. time.sleep(0.05)
  230. self._port.setDTR(True) # IO0=LOW
  231. self._port.setRTS(False) # EN=HIGH, chip out of reset
  232. if mode == 'esp32r0':
  233. # this is a workaround for a bug with the most
  234. # common auto reset circuit and Windows, if the EN
  235. # pin on the dev board does not have enough
  236. # capacitance. This workaround only works on
  237. # revision 0 ESP32 chips, it exploits a silicon
  238. # bug spurious watchdog reset.
  239. #
  240. # Details: https://github.com/espressif/esptool/issues/136
  241. time.sleep(0.4) # allow watchdog reset to occur
  242. time.sleep(0.05)
  243. self._port.setDTR(False) # IO0=HIGH, done
  244. self._port.timeout = 0.1
  245. last_exception = None
  246. for _ in xrange(4):
  247. try:
  248. self.flush_input()
  249. self._port.flushOutput()
  250. self.sync()
  251. self._port.timeout = 5
  252. return
  253. except FatalError as e:
  254. last_exception = e
  255. time.sleep(0.05)
  256. raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_exception))
  257. """ Read memory address in target """
  258. def read_reg(self, addr):
  259. # we don't call check_command here because read_reg() function is called
  260. # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
  261. # for different chip types (!)
  262. val, data = self.command(self.ESP_READ_REG, struct.pack('<I', addr))
  263. if data[0] != '\0':
  264. raise FatalError.WithResult("Failed to read register address %08x" % addr, data)
  265. return val
  266. """ Write to memory address in target """
  267. def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0):
  268. return self.check_command("write target memory", self.ESP_WRITE_REG,
  269. struct.pack('<IIII', addr, value, mask, delay_us))
  270. """ Start downloading an application image to RAM """
  271. def mem_begin(self, size, blocks, blocksize, offset):
  272. return self.check_command("enter RAM download mode", self.ESP_MEM_BEGIN,
  273. struct.pack('<IIII', size, blocks, blocksize, offset))
  274. """ Send a block of an image to RAM """
  275. def mem_block(self, data, seq):
  276. return self.check_command("write to target RAM", self.ESP_MEM_DATA,
  277. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  278. self.checksum(data))
  279. """ Leave download mode and run the application """
  280. def mem_finish(self, entrypoint=0):
  281. return self.check_command("leave RAM download mode", self.ESP_MEM_END,
  282. struct.pack('<II', int(entrypoint == 0), entrypoint))
  283. """ Start downloading to Flash (performs an erase)
  284. Returns number of blocks (of size self.FLASH_WRITE_SIZE) to write.
  285. """
  286. def flash_begin(self, size, offset):
  287. old_tmo = self._port.timeout
  288. num_blocks = (size + self.FLASH_WRITE_SIZE - 1) / self.FLASH_WRITE_SIZE
  289. erase_size = self.get_erase_size(offset, size)
  290. self._port.timeout = 20
  291. t = time.time()
  292. self.check_command("enter Flash download mode", self.ESP_FLASH_BEGIN,
  293. struct.pack('<IIII', erase_size, num_blocks, self.FLASH_WRITE_SIZE, offset))
  294. if size != 0 and not self.IS_STUB:
  295. print "Took %.2fs to erase flash block" % (time.time() - t)
  296. self._port.timeout = old_tmo
  297. return num_blocks
  298. """ Write block to flash """
  299. def flash_block(self, data, seq):
  300. self.check_command("write to target Flash after seq %d" % seq,
  301. self.ESP_FLASH_DATA,
  302. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  303. self.checksum(data))
  304. """ Leave flash mode and run/reboot """
  305. def flash_finish(self, reboot=False):
  306. pkt = struct.pack('<I', int(not reboot))
  307. # stub sends a reply to this command
  308. self.check_command("leave Flash mode", self.ESP_FLASH_END, pkt)
  309. """ Run application code in flash """
  310. def run(self, reboot=False):
  311. # Fake flash begin immediately followed by flash end
  312. self.flash_begin(0, 0)
  313. self.flash_finish(reboot)
  314. """ Read SPI flash manufacturer and device id """
  315. def flash_id(self):
  316. SPIFLASH_RDID = 0x9F
  317. return self.run_spiflash_command(SPIFLASH_RDID, b"", 24)
  318. def parse_flash_size_arg(self, arg):
  319. try:
  320. return self.FLASH_SIZES[arg]
  321. except KeyError:
  322. raise FatalError("Flash size '%s' is not supported by this chip type. Supported sizes: %s"
  323. % (arg, ", ".join(self.FLASH_SIZES.keys())))
  324. def run_stub(self, stub=None):
  325. if stub is None:
  326. if self.IS_STUB:
  327. raise FatalError("Not possible for a stub to load another stub (memory likely to overlap.)")
  328. stub = self.STUB_CODE
  329. # Upload
  330. print "Uploading stub..."
  331. for field in ['text', 'data']:
  332. if field in stub:
  333. offs = stub[field + "_start"]
  334. length = len(stub[field])
  335. blocks = (length + self.ESP_RAM_BLOCK - 1) / self.ESP_RAM_BLOCK
  336. self.mem_begin(length, blocks, self.ESP_RAM_BLOCK, offs)
  337. for seq in range(blocks):
  338. from_offs = seq * self.ESP_RAM_BLOCK
  339. to_offs = from_offs + self.ESP_RAM_BLOCK
  340. self.mem_block(stub[field][from_offs:to_offs], seq)
  341. print "Running stub..."
  342. self.mem_finish(stub['entry'])
  343. p = self.read()
  344. if p != 'OHAI':
  345. raise FatalError("Failed to start stub. Unexpected response: %s" % p)
  346. print "Stub running..."
  347. return self.STUB_CLASS(self)
  348. @stub_and_esp32_function_only
  349. def flash_defl_begin(self, size, compsize, offset):
  350. """ Start downloading compressed data to Flash (performs an erase)
  351. Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
  352. """
  353. old_tmo = self._port.timeout
  354. num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) / self.FLASH_WRITE_SIZE
  355. erase_blocks = (size + self.FLASH_WRITE_SIZE - 1) / self.FLASH_WRITE_SIZE
  356. self._port.timeout = 20
  357. t = time.time()
  358. print "Compressed %d bytes to %d..." % (size, compsize)
  359. self.check_command("enter compressed flash mode", self.ESP_FLASH_DEFL_BEGIN,
  360. struct.pack('<IIII', erase_blocks * self.FLASH_WRITE_SIZE, num_blocks, self.FLASH_WRITE_SIZE, offset))
  361. if size != 0 and not self.IS_STUB:
  362. # (stub erases as it writes, but ROM loaders erase on begin)
  363. print "Took %.2fs to erase flash block" % (time.time() - t)
  364. self._port.timeout = old_tmo
  365. return num_blocks
  366. """ Write block to flash, send compressed """
  367. @stub_and_esp32_function_only
  368. def flash_defl_block(self, data, seq):
  369. self.check_command("write compressed data to flash after seq %d" % seq,
  370. self.ESP_FLASH_DEFL_DATA, struct.pack('<IIII', len(data), seq, 0, 0) + data, self.checksum(data))
  371. """ Leave compressed flash mode and run/reboot """
  372. @stub_and_esp32_function_only
  373. def flash_defl_finish(self, reboot=False):
  374. if not reboot and not self.IS_STUB:
  375. # skip sending flash_finish to ROM loader, as this
  376. # exits the bootloader. Stub doesn't do this.
  377. return
  378. pkt = struct.pack('<I', int(not reboot))
  379. self.check_command("leave compressed flash mode", self.ESP_FLASH_DEFL_END, pkt)
  380. self.in_bootloader = False
  381. @stub_and_esp32_function_only
  382. def flash_md5sum(self, addr, size):
  383. # the MD5 command returns additional bytes in the standard
  384. # command reply slot
  385. res = self.check_command('calculate md5sum', self.ESP_SPI_FLASH_MD5, struct.pack('<IIII', addr, size, 0, 0))
  386. if len(res) == 32:
  387. return res # already hex formatted
  388. elif len(res) == 16:
  389. return hexify(res).lower()
  390. else:
  391. raise FatalError("MD5Sum command returned unexpected result: %r" % res)
  392. @stub_and_esp32_function_only
  393. def change_baud(self, baud):
  394. print "Changing baud rate to %d" % baud
  395. self.command(self.ESP_CHANGE_BAUDRATE, struct.pack('<II', baud, 0))
  396. print "Changed."
  397. self._port.baudrate = baud
  398. time.sleep(0.05) # get rid of crap sent during baud rate change
  399. self.flush_input()
  400. @stub_function_only
  401. def erase_flash(self):
  402. oldtimeout = self._port.timeout
  403. # depending on flash chip model the erase may take this long (maybe longer!)
  404. self._port.timeout = 128
  405. try:
  406. self.check_command("erase flash", self.ESP_ERASE_FLASH)
  407. finally:
  408. self._port.timeout = oldtimeout
  409. @stub_function_only
  410. def erase_region(self, offset, size):
  411. if offset % self.FLASH_SECTOR_SIZE != 0:
  412. raise FatalError("Offset to erase from must be a multiple of 4096")
  413. if size % self.FLASH_SECTOR_SIZE != 0:
  414. raise FatalError("Size of data to erase must be a multiple of 4096")
  415. self.check_command("erase region", self.ESP_ERASE_REGION, struct.pack('<II', offset, size))
  416. @stub_function_only
  417. def read_flash(self, offset, length, progress_fn=None):
  418. # issue a standard bootloader command to trigger the read
  419. self.check_command("read flash", self.ESP_READ_FLASH,
  420. struct.pack('<IIII',
  421. offset,
  422. length,
  423. self.FLASH_SECTOR_SIZE,
  424. 64))
  425. # now we expect (length / block_size) SLIP frames with the data
  426. data = ''
  427. while len(data) < length:
  428. p = self.read()
  429. data += p
  430. self.write(struct.pack('<I', len(data)))
  431. if progress_fn and (len(data) % 1024 == 0 or len(data) == length):
  432. progress_fn(len(data), length)
  433. if progress_fn:
  434. progress_fn(len(data), length)
  435. if len(data) > length:
  436. raise FatalError('Read more than expected')
  437. digest_frame = self.read()
  438. if len(digest_frame) != 16:
  439. raise FatalError('Expected digest, got: %s' % hexify(digest_frame))
  440. expected_digest = hexify(digest_frame).upper()
  441. digest = hashlib.md5(data).hexdigest().upper()
  442. if digest != expected_digest:
  443. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  444. return data
  445. def flash_spi_attach(self,is_hspi,is_legacy):
  446. """Send SPI attach command to enable the SPI flash pins
  447. ESP8266 ROM does this when you send flash_begin, ESP32 ROM
  448. has it as a SPI command.
  449. """
  450. # last 3 bytes in ESP_SPI_ATTACH argument are reserved values
  451. arg = struct.pack('<IBBBB', 1 if is_hspi else 0, 1 if is_legacy else 0, 0, 0, 0)
  452. self.check_command("configure SPI flash pins", ESP32ROM.ESP_SPI_ATTACH, arg)
  453. def flash_set_parameters(self, size):
  454. """Tell the ESP bootloader the parameters of the chip
  455. Corresponds to the "flashchip" data structure that the ROM
  456. has in RAM.
  457. 'size' is in bytes.
  458. All other flash parameters are currently hardcoded (on ESP8266
  459. these are mostly ignored by ROM code, on ESP32 I'm not sure.)
  460. """
  461. fl_id = 0
  462. total_size = size
  463. block_size = 64 * 1024
  464. sector_size = 4 * 1024
  465. page_size = 256
  466. status_mask = 0xffff
  467. self.check_command("set SPI params", ESP32ROM.ESP_SPI_SET_PARAMS,
  468. struct.pack('<IIIIII', fl_id, total_size, block_size, sector_size, page_size, status_mask))
  469. def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
  470. """Run an arbitrary SPI flash command.
  471. This function uses the "USR_COMMAND" functionality in the ESP
  472. SPI hardware, rather than the precanned commands supported by
  473. hardware. So the value of spiflash_command is an actual command
  474. byte, sent over the wire.
  475. After writing command byte, writes 'data' to MOSI and then
  476. reads back 'read_bits' of reply on MISO. Result is a number.
  477. """
  478. # SPI_USR register flags
  479. SPI_USR_COMMAND = (1 << 31)
  480. SPI_USR_MISO = (1 << 28)
  481. SPI_USR_MOSI = (1 << 27)
  482. # SPI registers, base address differs ESP32 vs 8266
  483. base = self.SPI_REG_BASE
  484. SPI_CMD_REG = base + 0x00
  485. SPI_USR_REG = base + 0x1C
  486. SPI_USR1_REG = base + 0x20
  487. SPI_USR2_REG = base + 0x24
  488. SPI_W0_REG = base + self.SPI_W0_OFFS
  489. # following two registers are ESP32 only
  490. if self.SPI_HAS_MOSI_DLEN_REG:
  491. # ESP32 has a more sophisticated wayto set up "user" commands
  492. def set_data_lengths(mosi_bits, miso_bits):
  493. SPI_MOSI_DLEN_REG = base + 0x28
  494. SPI_MISO_DLEN_REG = base + 0x2C
  495. if mosi_bits > 0:
  496. self.write_reg(SPI_MOSI_DLEN_REG, mosi_bits - 1)
  497. if miso_bits > 0:
  498. self.write_reg(SPI_MISO_DLEN_REG, miso_bits - 1)
  499. else:
  500. def set_data_lengths(mosi_bits, miso_bits):
  501. SPI_DATA_LEN_REG = SPI_USR1_REG
  502. SPI_MOSI_BITLEN_S = 17
  503. SPI_MISO_BITLEN_S = 8
  504. mosi_mask = 0 if (mosi_bits == 0) else (mosi_bits - 1)
  505. miso_mask = 0 if (miso_bits == 0) else (miso_bits - 1)
  506. self.write_reg(SPI_DATA_LEN_REG,
  507. (miso_mask << SPI_MISO_BITLEN_S) | (
  508. mosi_mask << SPI_MOSI_BITLEN_S))
  509. # SPI peripheral "command" bitmasks for SPI_CMD_REG
  510. SPI_CMD_USR = (1 << 18)
  511. # shift values
  512. SPI_USR2_DLEN_SHIFT = 28
  513. if read_bits > 32:
  514. raise FatalError("Reading more than 32 bits back from a SPI flash operation is unsupported")
  515. if len(data) > 64:
  516. raise FatalError("Writing more than 64 bytes of data with one SPI command is unsupported")
  517. data_bits = len(data) * 8
  518. old_spi_usr = self.read_reg(SPI_USR_REG)
  519. old_spi_usr2 = self.read_reg(SPI_USR2_REG)
  520. flags = SPI_USR_COMMAND
  521. if read_bits > 0:
  522. flags |= SPI_USR_MISO
  523. if data_bits > 0:
  524. flags |= SPI_USR_MOSI
  525. set_data_lengths(data_bits, read_bits)
  526. self.write_reg(SPI_USR_REG, flags)
  527. self.write_reg(SPI_USR2_REG,
  528. (7 << SPI_USR2_DLEN_SHIFT) | spiflash_command)
  529. if data_bits == 0:
  530. self.write_reg(SPI_W0_REG, 0) # clear data register before we read it
  531. else:
  532. if len(data) % 4 != 0: # pad to 32-bit multiple
  533. data += b'\0' * (4 - (len(data) % 4))
  534. words = struct.unpack("I" * (len(data) / 4), data)
  535. next_reg = SPI_W0_REG
  536. for word in words:
  537. self.write_reg(next_reg, word)
  538. next_reg += 4
  539. self.write_reg(SPI_CMD_REG, SPI_CMD_USR)
  540. def wait_done():
  541. for _ in xrange(10):
  542. if (self.read_reg(SPI_CMD_REG) & SPI_CMD_USR) == 0:
  543. return
  544. raise FatalError("SPI command did not complete in time")
  545. wait_done()
  546. status = self.read_reg(SPI_W0_REG)
  547. # restore some SPI controller registers
  548. self.write_reg(SPI_USR_REG, old_spi_usr)
  549. self.write_reg(SPI_USR2_REG, old_spi_usr2)
  550. return status
  551. def read_status(self, num_bytes=2):
  552. """Read up to 24 bits (num_bytes) of SPI flash status register contents
  553. via RDSR, RDSR2, RDSR3 commands
  554. Not all SPI flash supports all three commands. The upper 1 or 2
  555. bytes may be 0xFF.
  556. """
  557. SPIFLASH_RDSR = 0x05
  558. SPIFLASH_RDSR2 = 0x35
  559. SPIFLASH_RDSR3 = 0x15
  560. status = 0
  561. shift = 0
  562. for cmd in [SPIFLASH_RDSR, SPIFLASH_RDSR2, SPIFLASH_RDSR3][0:num_bytes]:
  563. status += self.run_spiflash_command(cmd, read_bits=8) << shift
  564. shift += 8
  565. return status
  566. def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
  567. """Write up to 24 bits (num_bytes) of new status register
  568. num_bytes can be 1, 2 or 3.
  569. Not all flash supports the additional commands to write the
  570. second and third byte of the status register. When writing 2
  571. bytes, esptool also sends a 16-byte WRSR command (as some
  572. flash types use this instead of WRSR2.)
  573. If the set_non_volatile flag is set, non-volatile bits will
  574. be set as well as volatile ones (WREN used instead of WEVSR).
  575. """
  576. SPIFLASH_WRSR = 0x01
  577. SPIFLASH_WRSR2 = 0x31
  578. SPIFLASH_WRSR3 = 0x11
  579. SPIFLASH_WEVSR = 0x50
  580. SPIFLASH_WREN = 0x06
  581. SPIFLASH_WRDI = 0x04
  582. enable_cmd = SPIFLASH_WREN if set_non_volatile else SPIFLASH_WEVSR
  583. # try using a 16-bit WRSR (not supported by all chips)
  584. # this may be redundant, but shouldn't hurt
  585. if num_bytes == 2:
  586. self.run_spiflash_command(enable_cmd)
  587. self.run_spiflash_command(SPIFLASH_WRSR, struct.pack("<H", new_status))
  588. # also try using individual commands (also not supported by all chips for num_bytes 2 & 3)
  589. for cmd in [SPIFLASH_WRSR, SPIFLASH_WRSR2, SPIFLASH_WRSR3][0:num_bytes]:
  590. self.run_spiflash_command(enable_cmd)
  591. self.run_spiflash_command(cmd, struct.pack("B", new_status & 0xFF))
  592. new_status >>= 8
  593. self.run_spiflash_command(SPIFLASH_WRDI)
  594. def hard_reset(self):
  595. self._port.setRTS(True) # EN->LOW
  596. time.sleep(0.1)
  597. self._port.setRTS(False)
  598. def soft_reset(self, stay_in_bootloader):
  599. if not self.IS_STUB:
  600. if stay_in_bootloader:
  601. return # ROM bootloader is already in bootloader!
  602. else:
  603. # 'run user code' is as close to a soft reset as we can do
  604. self.flash_begin(0, 0)
  605. self.flash_finish(False)
  606. else:
  607. if stay_in_bootloader:
  608. # soft resetting from the stub loader
  609. # will re-load the ROM bootloader
  610. self.flash_begin(0, 0)
  611. self.flash_finish(True)
  612. elif self.CHIP_NAME != "ESP8266":
  613. raise FatalError("Soft resetting is currently only supported on ESP8266")
  614. else:
  615. # running user code from stub loader requires some hacks
  616. # in the stub loader
  617. self.command(self.ESP_RUN_USER_CODE, wait_response=False)
  618. class ESP8266ROM(ESPLoader):
  619. """ Access class for ESP8266 ROM bootloader
  620. """
  621. CHIP_NAME = "ESP8266"
  622. IS_STUB = False
  623. DATE_REG_VALUE = 0x00062000
  624. # OTP ROM addresses
  625. ESP_OTP_MAC0 = 0x3ff00050
  626. ESP_OTP_MAC1 = 0x3ff00054
  627. ESP_OTP_MAC3 = 0x3ff0005c
  628. SPI_REG_BASE = 0x60000200
  629. SPI_W0_OFFS = 0x40
  630. SPI_HAS_MOSI_DLEN_REG = False
  631. FLASH_SIZES = {
  632. '512KB':0x00,
  633. '256KB':0x10,
  634. '1MB':0x20,
  635. '2MB':0x30,
  636. '4MB':0x40,
  637. '2MB-c1': 0x50,
  638. '4MB-c1':0x60,
  639. '4MB-c2':0x70}
  640. FLASH_HEADER_OFFSET = 0
  641. def flash_spi_attach(self, is_spi, is_legacy):
  642. if self.IS_STUB:
  643. super(ESP8266ROM, self).flash_spi_attach(is_spi, is_legacy)
  644. else:
  645. # ESP8266 ROM has no flash_spi_attach command in serial protocol,
  646. # but flash_begin will do it
  647. self.flash_begin(0, 0)
  648. def flash_set_parameters(self, size):
  649. # not implemented in ROM, but OK to silently skip for ROM
  650. if self.IS_STUB:
  651. super(ESP8266ROM, self).flash_set_parameters(size)
  652. def chip_id(self):
  653. """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """
  654. id0 = self.read_reg(self.ESP_OTP_MAC0)
  655. id1 = self.read_reg(self.ESP_OTP_MAC1)
  656. return (id0 >> 24) | ((id1 & MAX_UINT24) << 8)
  657. def read_mac(self):
  658. """ Read MAC from OTP ROM """
  659. mac0 = self.read_reg(self.ESP_OTP_MAC0)
  660. mac1 = self.read_reg(self.ESP_OTP_MAC1)
  661. mac3 = self.read_reg(self.ESP_OTP_MAC3)
  662. if (mac3 != 0):
  663. oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
  664. elif ((mac1 >> 16) & 0xff) == 0:
  665. oui = (0x18, 0xfe, 0x34)
  666. elif ((mac1 >> 16) & 0xff) == 1:
  667. oui = (0xac, 0xd0, 0x74)
  668. else:
  669. raise FatalError("Unknown OUI")
  670. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  671. def get_erase_size(self, offset, size):
  672. """ Calculate an erase size given a specific size in bytes.
  673. Provides a workaround for the bootloader erase bug."""
  674. sectors_per_block = 16
  675. sector_size = self.FLASH_SECTOR_SIZE
  676. num_sectors = (size + sector_size - 1) / sector_size
  677. start_sector = offset / sector_size
  678. head_sectors = sectors_per_block - (start_sector % sectors_per_block)
  679. if num_sectors < head_sectors:
  680. head_sectors = num_sectors
  681. if num_sectors < 2 * head_sectors:
  682. return (num_sectors + 1) / 2 * sector_size
  683. else:
  684. return (num_sectors - head_sectors) * sector_size
  685. class ESP8266StubLoader(ESP8266ROM):
  686. """ Access class for ESP8266 stub loader, runs on top of ROM.
  687. """
  688. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  689. IS_STUB = True
  690. def __init__(self, rom_loader):
  691. self._port = rom_loader._port
  692. self.flush_input() # resets _slip_reader
  693. def get_erase_size(self, offset, size):
  694. return size # stub doesn't have same size bug as ROM loader
  695. ESP8266ROM.STUB_CLASS = ESP8266StubLoader
  696. class ESP32ROM(ESPLoader):
  697. """Access class for ESP32 ROM bootloader
  698. """
  699. CHIP_NAME = "ESP32"
  700. IS_STUB = False
  701. DATE_REG_VALUE = 0x15122500
  702. IROM_MAP_START = 0x400d0000
  703. IROM_MAP_END = 0x40400000
  704. DROM_MAP_START = 0x3F400000
  705. DROM_MAP_END = 0x3F700000
  706. # ESP32 uses a 4 byte status reply
  707. STATUS_BYTES_LENGTH = 4
  708. SPI_REG_BASE = 0x60002000
  709. EFUSE_REG_BASE = 0x6001a000
  710. SPI_W0_OFFS = 0x80
  711. SPI_HAS_MOSI_DLEN_REG = True
  712. FLASH_SIZES = {
  713. '1MB':0x00,
  714. '2MB':0x10,
  715. '4MB':0x20,
  716. '8MB':0x30,
  717. '16MB':0x40
  718. }
  719. FLASH_HEADER_OFFSET = 0x1000
  720. def read_efuse(self, n):
  721. """ Read the nth word of the ESP3x EFUSE region. """
  722. return self.read_reg(self.EFUSE_REG_BASE + (4 * n))
  723. def chip_id(self):
  724. word16 = self.read_efuse(1)
  725. word17 = self.read_efuse(2)
  726. return ((word17 & MAX_UINT24) << 24) | (word16 >> 8) & MAX_UINT24
  727. def read_mac(self):
  728. """ Read MAC from EFUSE region """
  729. words = [self.read_efuse(1), self.read_efuse(2)]
  730. bitstring = struct.pack(">II", *words)
  731. return tuple(ord(b) for b in bitstring[:6]) # trim 2 byte CRC
  732. def get_erase_size(self, offset, size):
  733. return size
  734. class ESP32StubLoader(ESP32ROM):
  735. """ Access class for ESP32 stub loader, runs on top of ROM.
  736. """
  737. FLASH_WRITE_SIZE = 0x4000 # matches MAX_WRITE_BLOCK in stub_loader.c
  738. STATUS_BYTES_LENGTH = 2 # same as ESP8266, different to ESP32 ROM
  739. IS_STUB = True
  740. def __init__(self, rom_loader):
  741. self._port = rom_loader._port
  742. self.flush_input() # resets _slip_reader
  743. ESP32ROM.STUB_CLASS = ESP32StubLoader
  744. class ESPBOOTLOADER(object):
  745. """ These are constants related to software ESP bootloader, working with 'v2' image files """
  746. # First byte of the "v2" application image
  747. IMAGE_V2_MAGIC = 0xea
  748. # First 'segment' value in a "v2" application image, appears to be a constant version value?
  749. IMAGE_V2_SEGMENT = 4
  750. def LoadFirmwareImage(chip, filename):
  751. """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
  752. original ROM firmware images (ESPFirmwareImage) or "v2" OTA bootloader images.
  753. Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2).
  754. """
  755. with open(filename, 'rb') as f:
  756. if chip == 'esp32':
  757. return ESP32FirmwareImage(f)
  758. else: # Otherwise, ESP8266 so look at magic to determine the image type
  759. magic = ord(f.read(1))
  760. f.seek(0)
  761. if magic == ESPLoader.ESP_IMAGE_MAGIC:
  762. return ESPFirmwareImage(f)
  763. elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
  764. return OTAFirmwareImage(f)
  765. else:
  766. raise FatalError("Invalid image magic number: %d" % magic)
  767. class ImageSegment(object):
  768. """ Wrapper class for a segment in an ESP image
  769. (very similar to a section in an ELFImage also) """
  770. def __init__(self, addr, data, file_offs=None):
  771. self.addr = addr
  772. # pad all ImageSegments to at least 4 bytes length
  773. pad_mod = len(data) % 4
  774. if pad_mod != 0:
  775. data += "\x00" * (4 - pad_mod)
  776. self.data = data
  777. self.file_offs = file_offs
  778. self.include_in_checksum = True
  779. def copy_with_new_addr(self, new_addr):
  780. """ Return a new ImageSegment with same data, but mapped at
  781. a new address. """
  782. return ImageSegment(new_addr, self.data, 0)
  783. def __repr__(self):
  784. r = "len 0x%05x load 0x%08x" % (len(self.data), self.addr)
  785. if self.file_offs is not None:
  786. r += " file_offs 0x%08x" % (self.file_offs)
  787. return r
  788. class ELFSection(ImageSegment):
  789. """ Wrapper class for a section in an ELF image, has a section
  790. name as well as the common properties of an ImageSegment. """
  791. def __init__(self, name, addr, data):
  792. super(ELFSection, self).__init__(addr, data)
  793. self.name = name
  794. def __repr__(self):
  795. return "%s %s" % (self.name, super(ELFSection, self).__repr__())
  796. class BaseFirmwareImage(object):
  797. SEG_HEADER_LEN = 8
  798. """ Base class with common firmware image functions """
  799. def __init__(self):
  800. self.segments = []
  801. self.entrypoint = 0
  802. def load_common_header(self, load_file, expected_magic):
  803. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  804. if magic != expected_magic or segments > 16:
  805. raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
  806. return segments
  807. def load_segment(self, f, is_irom_segment=False):
  808. """ Load the next segment from the image file """
  809. file_offs = f.tell()
  810. (offset, size) = struct.unpack('<II', f.read(8))
  811. self.warn_if_unusual_segment(offset, size, is_irom_segment)
  812. segment_data = f.read(size)
  813. if len(segment_data) < size:
  814. raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
  815. segment = ImageSegment(offset, segment_data, file_offs)
  816. self.segments.append(segment)
  817. return segment
  818. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  819. if not is_irom_segment:
  820. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  821. print('WARNING: Suspicious segment 0x%x, length %d' % (offset, size))
  822. def save_segment(self, f, segment, checksum=None):
  823. """ Save the next segment to the image file, return next checksum value if provided """
  824. f.write(struct.pack('<II', segment.addr, len(segment.data)))
  825. f.write(segment.data)
  826. if checksum is not None:
  827. return ESPLoader.checksum(segment.data, checksum)
  828. def read_checksum(self, f):
  829. """ Return ESPLoader checksum from end of just-read image """
  830. # Skip the padding. The checksum is stored in the last byte so that the
  831. # file is a multiple of 16 bytes.
  832. align_file_position(f, 16)
  833. return ord(f.read(1))
  834. def calculate_checksum(self):
  835. """ Calculate checksum of loaded image, based on segments in
  836. segment array.
  837. """
  838. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  839. for seg in self.segments:
  840. if seg.include_in_checksum:
  841. checksum = ESPLoader.checksum(seg.data, checksum)
  842. return checksum
  843. def append_checksum(self, f, checksum):
  844. """ Append ESPLoader checksum to the just-written image """
  845. align_file_position(f, 16)
  846. f.write(struct.pack('B', checksum))
  847. def write_common_header(self, f, segments):
  848. f.write(struct.pack('<BBBBI', ESPLoader.ESP_IMAGE_MAGIC, len(segments),
  849. self.flash_mode, self.flash_size_freq, self.entrypoint))
  850. def is_irom_addr(self, addr):
  851. """ Returns True if an address starts in the irom region.
  852. Valid for ESP8266 only.
  853. """
  854. return ESP8266ROM.IROM_MAP_START <= addr < ESP8266ROM.IROM_MAP_END
  855. def get_irom_segment(self):
  856. irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)]
  857. if len(irom_segments) > 0:
  858. if len(irom_segments) != 1:
  859. raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
  860. return irom_segments[0]
  861. return None
  862. def get_non_irom_segments(self):
  863. irom_segment = self.get_irom_segment()
  864. return [s for s in self.segments if s != irom_segment]
  865. class ESPFirmwareImage(BaseFirmwareImage):
  866. """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
  867. ROM_LOADER = ESP8266ROM
  868. def __init__(self, load_file=None):
  869. super(ESPFirmwareImage, self).__init__()
  870. self.flash_mode = 0
  871. self.flash_size_freq = 0
  872. self.version = 1
  873. if load_file is not None:
  874. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  875. for _ in xrange(segments):
  876. self.load_segment(load_file)
  877. self.checksum = self.read_checksum(load_file)
  878. def default_output_name(self, input_file):
  879. """ Derive a default output name from the ELF name. """
  880. return input_file + '-'
  881. def save(self, basename):
  882. """ Save a set of V1 images for flashing. Parameter is a base filename. """
  883. # IROM data goes in its own plain binary file
  884. irom_segment = self.get_irom_segment()
  885. if irom_segment is not None:
  886. with open("%s0x%05x.bin" % (basename, irom_segment.addr - ESP8266ROM.IROM_MAP_START), "wb") as f:
  887. f.write(irom_segment.data)
  888. # everything but IROM goes at 0x00000 in an image file
  889. normal_segments = self.get_non_irom_segments()
  890. with open("%s0x00000.bin" % basename, 'wb') as f:
  891. self.write_common_header(f, normal_segments)
  892. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  893. for segment in normal_segments:
  894. checksum = self.save_segment(f, segment, checksum)
  895. self.append_checksum(f, checksum)
  896. class OTAFirmwareImage(BaseFirmwareImage):
  897. """ 'Version 2' firmware image, segments loaded by software bootloader stub
  898. (ie Espressif bootloader or rboot)
  899. """
  900. ROM_LOADER = ESP8266ROM
  901. def __init__(self, load_file=None):
  902. super(OTAFirmwareImage, self).__init__()
  903. self.version = 2
  904. if load_file is not None:
  905. segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC)
  906. if segments != ESPBOOTLOADER.IMAGE_V2_SEGMENT:
  907. # segment count is not really segment count here, but we expect to see '4'
  908. print 'Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments
  909. # irom segment comes before the second header
  910. #
  911. # the file is saved in the image with a zero load address
  912. # in the header, so we need to calculate a load address
  913. irom_segment = self.load_segment(load_file, True)
  914. # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_Addr + 8
  915. irom_segment.addr = 0
  916. irom_segment.include_in_checksum = False
  917. first_flash_mode = self.flash_mode
  918. first_flash_size_freq = self.flash_size_freq
  919. first_entrypoint = self.entrypoint
  920. # load the second header
  921. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  922. if first_flash_mode != self.flash_mode:
  923. print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  924. % (first_flash_mode, self.flash_mode))
  925. if first_flash_size_freq != self.flash_size_freq:
  926. print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  927. % (first_flash_size_freq, self.flash_size_freq))
  928. if first_entrypoint != self.entrypoint:
  929. print('WARNING: Entrypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
  930. % (first_entrypoint, self.entrypoint))
  931. # load all the usual segments
  932. for _ in xrange(segments):
  933. self.load_segment(load_file)
  934. self.checksum = self.read_checksum(load_file)
  935. def default_output_name(self, input_file):
  936. """ Derive a default output name from the ELF name. """
  937. irom_segment = self.get_irom_segment()
  938. if irom_segment is not None:
  939. irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
  940. else:
  941. irom_offs = 0
  942. return "%s-0x%05x.bin" % (os.path.splitext(input_file)[0],
  943. irom_offs & ~(ESPLoader.FLASH_SECTOR_SIZE - 1))
  944. def save(self, filename):
  945. with open(filename, 'wb') as f:
  946. # Save first header for irom0 segment
  947. f.write(struct.pack('<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
  948. self.flash_mode, self.flash_size_freq, self.entrypoint))
  949. irom_segment = self.get_irom_segment()
  950. if irom_segment is not None:
  951. # save irom0 segment, make sure it has load addr 0 in the file
  952. irom_segment = irom_segment.copy_with_new_addr(0)
  953. self.save_segment(f, irom_segment)
  954. # second header, matches V1 header and contains loadable segments
  955. normal_segments = self.get_non_irom_segments()
  956. self.write_common_header(f, normal_segments)
  957. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  958. for segment in normal_segments:
  959. checksum = self.save_segment(f, segment, checksum)
  960. self.append_checksum(f, checksum)
  961. class ESP32FirmwareImage(BaseFirmwareImage):
  962. """ ESP32 firmware image is very similar to V1 ESP8266 image,
  963. except with an additional 16 byte reserved header at top of image,
  964. and because of new flash mapping capabilities the flash-mapped regions
  965. can be placed in the normal image (just @ 64kB padded offsets).
  966. """
  967. ROM_LOADER = ESP32ROM
  968. def __init__(self, load_file=None):
  969. super(ESP32FirmwareImage, self).__init__()
  970. self.flash_mode = 0
  971. self.flash_size_freq = 0
  972. self.version = 1
  973. self.encrypt_flag = False
  974. if load_file is not None:
  975. segments = self.load_common_header(load_file, ESPLoader.ESP_IMAGE_MAGIC)
  976. additional_header = list(struct.unpack("B" * 16, load_file.read(16)))
  977. self.encrypt_flag = (additional_header[0] == 0x01)
  978. # check remaining 14 bytes are unused
  979. if additional_header[2:] != [0] * 14:
  980. print "WARNING: ESP32 image header contains unknown flags. Possibly this image is from a newer version of esptool.py"
  981. for i in xrange(segments):
  982. self.load_segment(load_file)
  983. self.checksum = self.read_checksum(load_file)
  984. def is_flash_addr(self, addr):
  985. return (ESP32ROM.IROM_MAP_START <= addr < ESP32ROM.IROM_MAP_END) \
  986. or (ESP32ROM.DROM_MAP_START <= addr < ESP32ROM.DROM_MAP_END)
  987. def default_output_name(self, input_file):
  988. """ Derive a default output name from the ELF name. """
  989. return "%s.bin" % (os.path.splitext(input_file)[0])
  990. def warn_if_unusual_segment(self, offset, size, is_irom_segment):
  991. pass # TODO: add warnings for ESP32 segment offset/size combinations that are wrong
  992. def save(self, filename):
  993. padding_segments = 0
  994. with open(filename, 'wb') as f:
  995. self.write_common_header(f, self.segments)
  996. f.write(b'\x01' if self.encrypt_flag else b'\x00')
  997. # remaining 15 bytes of header are unused
  998. f.write(b'\x00' * 15)
  999. checksum = ESPLoader.ESP_CHECKSUM_MAGIC
  1000. last_addr = None
  1001. for segment in sorted(self.segments, key=lambda s:s.addr):
  1002. # IROM/DROM segment flash mappings need to align on
  1003. # 64kB boundaries.
  1004. #
  1005. # TODO: intelligently order segments to reduce wastage
  1006. # by squeezing smaller DRAM/IRAM segments into the
  1007. # 64kB padding space.
  1008. IROM_ALIGN = 65536
  1009. # check for multiple ELF sections that live in the same flash mapping region.
  1010. # this is usually a sign of a broken linker script, but if you have a legitimate
  1011. # use case then let us know (we can merge segments here, but as a rule you probably
  1012. # want to merge them in your linker script.)
  1013. if last_addr is not None and self.is_flash_addr(last_addr) \
  1014. and self.is_flash_addr(segment.addr) and segment.addr // IROM_ALIGN == last_addr // IROM_ALIGN:
  1015. raise FatalError(("Segment loaded at 0x%08x lands in same 64KB flash mapping as segment loaded at 0x%08x. " +
  1016. "Can't generate binary. Suggest changing linker script or ELF to merge sections.") %
  1017. (segment.addr, last_addr))
  1018. last_addr = segment.addr
  1019. if self.is_flash_addr(segment.addr):
  1020. # Actual alignment required for the segment header: positioned so that
  1021. # after we write the next 8 byte header, file_offs % IROM_ALIGN == segment.addr % IROM_ALIGN
  1022. #
  1023. # (this is because the segment's vaddr may not be IROM_ALIGNed, more likely is aligned
  1024. # IROM_ALIGN+0x10 to account for longest possible header.
  1025. align_past = (segment.addr % IROM_ALIGN) - self.SEG_HEADER_LEN
  1026. assert (align_past + self.SEG_HEADER_LEN) == (segment.addr % IROM_ALIGN)
  1027. # subtract SEG_HEADER_LEN a second time, as the padding block has a header as well
  1028. pad_len = (IROM_ALIGN - (f.tell() % IROM_ALIGN)) + align_past - self.SEG_HEADER_LEN
  1029. if pad_len < 0:
  1030. pad_len += IROM_ALIGN
  1031. if pad_len > 0:
  1032. null = ImageSegment(0, '\x00' * pad_len, f.tell())
  1033. checksum = self.save_segment(f, null, checksum)
  1034. padding_segments += 1
  1035. # verify that after the 8 byte header is added, were are at the correct offset relative to the segment's vaddr
  1036. assert (f.tell() + 8) % IROM_ALIGN == segment.addr % IROM_ALIGN
  1037. checksum = self.save_segment(f, segment, checksum)
  1038. self.append_checksum(f, checksum)
  1039. # kinda hacky: go back to the initial header and write the new segment count
  1040. # that includes padding segments. Luckily(?) this header is not checksummed
  1041. f.seek(1)
  1042. f.write(chr(len(self.segments) + padding_segments))
  1043. class ELFFile(object):
  1044. SEC_TYPE_PROGBITS = 0x01
  1045. SEC_TYPE_STRTAB = 0x03
  1046. def __init__(self, name):
  1047. # Load sections from the ELF file
  1048. self.name = name
  1049. with open(self.name, 'rb') as f:
  1050. self._read_elf_file(f)
  1051. def get_section(self, section_name):
  1052. for s in self.sections:
  1053. if s.name == section_name:
  1054. return s
  1055. raise ValueError("No section %s in ELF file" % section_name)
  1056. def _read_elf_file(self, f):
  1057. # read the ELF file header
  1058. LEN_FILE_HEADER = 0x34
  1059. try:
  1060. (ident,_type,machine,_version,
  1061. self.entrypoint,_phoff,shoff,_flags,
  1062. _ehsize, _phentsize,_phnum,_shentsize,
  1063. _shnum,shstrndx) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
  1064. except struct.error as e:
  1065. raise FatalError("Failed to read a valid ELF header from %s: %s" % (self.name, e))
  1066. if ident[0] != '\x7f' or ident[1:4] != 'ELF':
  1067. raise FatalError("%s has invalid ELF magic header" % self.name)
  1068. if machine != 0x5e:
  1069. raise FatalError("%s does not appear to be an Xtensa ELF file. e_machine=%04x" % (self.name, machine))
  1070. self._read_sections(f, shoff, shstrndx)
  1071. def _read_sections(self, f, section_header_offs, shstrndx):
  1072. f.seek(section_header_offs)
  1073. section_header = f.read()
  1074. LEN_SEC_HEADER = 0x28
  1075. if len(section_header) == 0:
  1076. raise FatalError("No section header found at offset %04x in ELF file." % section_header_offs)
  1077. if len(section_header) % LEN_SEC_HEADER != 0:
  1078. print 'WARNING: Unexpected ELF section header length %04x is not mod-%02x' % (len(section_header),LEN_SEC_HEADER)
  1079. # walk through the section header and extract all sections
  1080. section_header_offsets = range(0, len(section_header), LEN_SEC_HEADER)
  1081. def read_section_header(offs):
  1082. name_offs,sec_type,_flags,lma,sec_offs,size = struct.unpack_from("<LLLLLL", section_header[offs:])
  1083. return (name_offs, sec_type, lma, size, sec_offs)
  1084. all_sections = [read_section_header(offs) for offs in section_header_offsets]
  1085. prog_sections = [s for s in all_sections if s[1] == ELFFile.SEC_TYPE_PROGBITS]
  1086. # search for the string table section
  1087. if not shstrndx * LEN_SEC_HEADER in section_header_offsets:
  1088. raise FatalError("ELF file has no STRTAB section at shstrndx %d" % shstrndx)
  1089. _,sec_type,_,sec_size,sec_offs = read_section_header(shstrndx * LEN_SEC_HEADER)
  1090. if sec_type != ELFFile.SEC_TYPE_STRTAB:
  1091. print 'WARNING: ELF file has incorrect STRTAB section type 0x%02x' % sec_type
  1092. f.seek(sec_offs)
  1093. string_table = f.read(sec_size)
  1094. # build the real list of ELFSections by reading the actual section names from the
  1095. # string table section, and actual data for each section from the ELF file itself
  1096. def lookup_string(offs):
  1097. raw = string_table[offs:]
  1098. return raw[:raw.index('\x00')]
  1099. def read_data(offs,size):
  1100. f.seek(offs)
  1101. return f.read(size)
  1102. prog_sections = [ELFSection(lookup_string(n_offs), lma, read_data(offs, size)) for (n_offs, _type, lma, size, offs) in prog_sections
  1103. if lma != 0]
  1104. self.sections = prog_sections
  1105. def slip_reader(port):
  1106. """Generator to read SLIP packets from a serial port.
  1107. Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
  1108. Designed to avoid too many calls to serial.read(1), which can bog
  1109. down on slow systems.
  1110. """
  1111. partial_packet = None
  1112. in_escape = False
  1113. while True:
  1114. waiting = port.inWaiting()
  1115. read_bytes = port.read(1 if waiting == 0 else waiting)
  1116. if read_bytes == '':
  1117. raise FatalError("Timed out waiting for packet %s" % ("header" if partial_packet is None else "content"))
  1118. for b in read_bytes:
  1119. if partial_packet is None: # waiting for packet header
  1120. if b == '\xc0':
  1121. partial_packet = ""
  1122. else:
  1123. raise FatalError('Invalid head of packet (%r)' % b)
  1124. elif in_escape: # part-way through escape sequence
  1125. in_escape = False
  1126. if b == '\xdc':
  1127. partial_packet += '\xc0'
  1128. elif b == '\xdd':
  1129. partial_packet += '\xdb'
  1130. else:
  1131. raise FatalError('Invalid SLIP escape (%r%r)' % ('\xdb', b))
  1132. elif b == '\xdb': # start of escape sequence
  1133. in_escape = True
  1134. elif b == '\xc0': # end of packet
  1135. yield partial_packet
  1136. partial_packet = None
  1137. else: # normal byte in packet
  1138. partial_packet += b
  1139. def arg_auto_int(x):
  1140. return int(x, 0)
  1141. def div_roundup(a, b):
  1142. """ Return a/b rounded up to nearest integer,
  1143. equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
  1144. without possible floating point accuracy errors.
  1145. """
  1146. return (int(a) + int(b) - 1) / int(b)
  1147. def align_file_position(f, size):
  1148. """ Align the position in the file to the next block of specified size """
  1149. align = (size - 1) - (f.tell() % size)
  1150. f.seek(align, 1)
  1151. def flash_size_bytes(size):
  1152. """ Given a flash size of the type passed in args.flash_size
  1153. (ie 512KB or 1MB) then return the size in bytes.
  1154. """
  1155. if "MB" in size:
  1156. return int(size[:size.index("MB")]) * 1024 * 1024
  1157. elif "KB" in size:
  1158. return int(size[:size.index("KB")]) * 1024
  1159. else:
  1160. raise FatalError("Unknown size %s" % size)
  1161. def hexify(s):
  1162. return ''.join('%02X' % ord(c) for c in s)
  1163. def unhexify(hs):
  1164. s = ''
  1165. for i in range(0, len(hs) - 1, 2):
  1166. s += chr(int(hs[i] + hs[i + 1], 16))
  1167. return s
  1168. class FatalError(RuntimeError):
  1169. """
  1170. Wrapper class for runtime errors that aren't caused by internal bugs, but by
  1171. ESP8266 responses or input content.
  1172. """
  1173. def __init__(self, message):
  1174. RuntimeError.__init__(self, message)
  1175. @staticmethod
  1176. def WithResult(message, result):
  1177. """
  1178. Return a fatal error object that appends the hex values of
  1179. 'result' as a string formatted argument.
  1180. """
  1181. message += " (result was %s)" % ", ".join(hex(ord(x)) for x in result)
  1182. return FatalError(message)
  1183. class NotImplementedInROMError(FatalError):
  1184. """
  1185. Wrapper class for the error thrown when a particular ESP bootloader function
  1186. is not implemented in the ROM bootloader.
  1187. """
  1188. def __init__(self, bootloader, func):
  1189. FatalError.__init__(self, "%s ROM does not support function %s." % (bootloader.CHIP_NAME, func.func_name))
  1190. # "Operation" commands, executable at command line. One function each
  1191. #
  1192. # Each function takes either two args (<ESPLoader instance>, <args>) or a single <args>
  1193. # argument.
  1194. def load_ram(esp, args):
  1195. image = LoadFirmwareImage(esp, args.filename)
  1196. print 'RAM boot...'
  1197. for (offset, size, data) in image.segments:
  1198. print 'Downloading %d bytes at %08x...' % (size, offset),
  1199. sys.stdout.flush()
  1200. esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset)
  1201. seq = 0
  1202. while len(data) > 0:
  1203. esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
  1204. data = data[esp.ESP_RAM_BLOCK:]
  1205. seq += 1
  1206. print 'done!'
  1207. print 'All segments done, executing at %08x' % image.entrypoint
  1208. esp.mem_finish(image.entrypoint)
  1209. def read_mem(esp, args):
  1210. print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address))
  1211. def write_mem(esp, args):
  1212. esp.write_reg(args.address, args.value, args.mask, 0)
  1213. print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address)
  1214. def dump_mem(esp, args):
  1215. f = file(args.filename, 'wb')
  1216. for i in xrange(args.size / 4):
  1217. d = esp.read_reg(args.address + (i * 4))
  1218. f.write(struct.pack('<I', d))
  1219. if f.tell() % 1024 == 0:
  1220. print '\r%d bytes read... (%d %%)' % (f.tell(),
  1221. f.tell() * 100 / args.size),
  1222. sys.stdout.flush()
  1223. print 'Done!'
  1224. def detect_flash_size(esp, args):
  1225. if args.flash_size == 'detect':
  1226. flash_id = esp.flash_id()
  1227. size_id = flash_id >> 16
  1228. args.flash_size = {0x12: '256KB', 0x13: '512KB', 0x14: '1MB', 0x15: '2MB', 0x16: '4MB', 0x17: '8MB', 0x18: '16MB'}.get(size_id)
  1229. if args.flash_size is None:
  1230. print 'Warning: Could not auto-detect Flash size (FlashID=0x%x, SizeID=0x%x), defaulting to 4m' % (flash_id, size_id)
  1231. args.flash_size = '4m'
  1232. else:
  1233. print 'Auto-detected Flash size:', args.flash_size
  1234. def write_flash(esp, args):
  1235. """Write data to flash
  1236. """
  1237. detect_flash_size(esp, args)
  1238. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1239. flash_size_freq = esp.parse_flash_size_arg(args.flash_size)
  1240. flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1241. flash_info = struct.pack('BB', flash_mode, flash_size_freq)
  1242. # verify file sizes fit in flash
  1243. flash_end = flash_size_bytes(args.flash_size)
  1244. for address, argfile in args.addr_filename:
  1245. argfile.seek(0,2) # seek to end
  1246. if address + argfile.tell() > flash_end:
  1247. raise FatalError(("File %s (length %d) at offset %d will not fit in %d bytes of flash. " +
  1248. "Use --flash-size argument, or change flashing address.")
  1249. % (argfile.name, argfile.tell(), address, flash_end))
  1250. argfile.seek(0)
  1251. for address, argfile in args.addr_filename:
  1252. if args.no_stub:
  1253. print 'Erasing flash...'
  1254. image = argfile.read()
  1255. # Update header with flash parameters
  1256. if address == esp.FLASH_HEADER_OFFSET and image[0] == '\xe9':
  1257. image = image[0:2] + flash_info + image[4:]
  1258. calcmd5 = hashlib.md5(image).hexdigest()
  1259. uncsize = len(image)
  1260. if args.compress:
  1261. uncimage = image
  1262. image = zlib.compress(uncimage, 9)
  1263. blocks = esp.flash_defl_begin(uncsize, len(image), address)
  1264. else:
  1265. blocks = esp.flash_begin(uncsize, address)
  1266. argfile.seek(0) # in case we need it again
  1267. seq = 0
  1268. written = 0
  1269. t = time.time()
  1270. header_block = None
  1271. while len(image) > 0:
  1272. print '\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.FLASH_WRITE_SIZE, 100 * (seq + 1) / blocks),
  1273. sys.stdout.flush()
  1274. block = image[0:esp.FLASH_WRITE_SIZE]
  1275. if args.compress:
  1276. esp.flash_defl_block(block, seq)
  1277. else:
  1278. # Pad the last block
  1279. block = block + '\xff' * (esp.FLASH_WRITE_SIZE - len(block))
  1280. esp.flash_block(block, seq)
  1281. image = image[esp.FLASH_WRITE_SIZE:]
  1282. seq += 1
  1283. written += len(block)
  1284. t = time.time() - t
  1285. speed_msg = ""
  1286. if args.compress:
  1287. if t > 0.0:
  1288. speed_msg = " (effective %.1f kbit/s)" % (uncsize / t * 8 / 1000)
  1289. print '\rWrote %d bytes (%d compressed) at 0x%08x in %.1f seconds%s...' % (uncsize, written, address, t, speed_msg)
  1290. else:
  1291. if t > 0.0:
  1292. speed_msg = " (%.1f kbit/s)" % (written / t * 8 / 1000)
  1293. print '\rWrote %d bytes at 0x%08x in %.1f seconds%s...' % (written, address, t, speed_msg)
  1294. try:
  1295. res = esp.flash_md5sum(address, uncsize)
  1296. if res != calcmd5:
  1297. print 'File md5: %s' % calcmd5
  1298. print 'Flash md5: %s' % res
  1299. print 'MD5 of 0xFF is %s' % (hashlib.md5(b'\xFF' * uncsize).hexdigest())
  1300. raise FatalError("MD5 of file does not match data in flash!")
  1301. else:
  1302. print 'Hash of data verified.'
  1303. except NotImplementedInROMError:
  1304. pass
  1305. print '\nLeaving...'
  1306. if esp.IS_STUB:
  1307. # skip sending flash_finish to ROM loader here,
  1308. # as it causes the loader to exit and run user code
  1309. esp.flash_begin(0, 0)
  1310. if args.compress:
  1311. esp.flash_defl_finish(False)
  1312. else:
  1313. esp.flash_finish(False)
  1314. if args.verify:
  1315. print 'Verifying just-written flash...'
  1316. verify_flash(esp, args, header_block)
  1317. def image_info(args):
  1318. image = LoadFirmwareImage(args.chip, args.filename)
  1319. print('Image version: %d' % image.version)
  1320. print('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set'
  1321. print '%d segments' % len(image.segments)
  1322. print
  1323. idx = 0
  1324. for seg in image.segments:
  1325. idx += 1
  1326. print 'Segment %d: %r' % (idx, seg)
  1327. calc_checksum = image.calculate_checksum()
  1328. print 'Checksum: %02x (%s)' % (image.checksum,
  1329. 'valid' if image.checksum == calc_checksum else 'invalid - calculated %02x' % calc_checksum)
  1330. def make_image(args):
  1331. image = ESPFirmwareImage()
  1332. if len(args.segfile) == 0:
  1333. raise FatalError('No segments specified')
  1334. if len(args.segfile) != len(args.segaddr):
  1335. raise FatalError('Number of specified files does not match number of specified addresses')
  1336. for (seg, addr) in zip(args.segfile, args.segaddr):
  1337. data = file(seg, 'rb').read()
  1338. image.segments.append(ImageSegment(addr, data))
  1339. image.entrypoint = args.entrypoint
  1340. image.save(args.output)
  1341. def elf2image(args):
  1342. e = ELFFile(args.input)
  1343. if args.chip == 'auto': # Default to ESP8266 for backwards compatibility
  1344. print "Creating image for ESP8266..."
  1345. args.chip == 'esp8266'
  1346. if args.chip != 'esp32':
  1347. if args.set_encrypt_flag:
  1348. raise FatalError("--encrypt-flag only applies to ESP32 images")
  1349. if args.chip == 'esp32':
  1350. image = ESP32FirmwareImage()
  1351. elif args.version == '1': # ESP8266
  1352. image = ESPFirmwareImage()
  1353. else:
  1354. image = OTAFirmwareImage()
  1355. image.entrypoint = e.entrypoint
  1356. image.segments = e.sections # ELFSection is a subclass of ImageSegment
  1357. image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1358. image.flash_size_freq = image.ROM_LOADER.FLASH_SIZES[args.flash_size]
  1359. image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1360. image.encrypt_flag = args.set_encrypt_flag
  1361. if args.output is None:
  1362. args.output = image.default_output_name(args.input)
  1363. image.save(args.output)
  1364. def read_mac(esp, args):
  1365. mac = esp.read_mac()
  1366. def print_mac(label, mac):
  1367. print '%s: %s' % (label, ':'.join(map(lambda x: '%02x' % x, mac)))
  1368. print_mac("MAC", mac)
  1369. def chip_id(esp, args):
  1370. chipid = esp.chip_id()
  1371. print 'Chip ID: 0x%08x' % chipid
  1372. def erase_flash(esp, args):
  1373. print 'Erasing flash (this may take a while)...'
  1374. t = time.time()
  1375. esp.erase_flash()
  1376. print 'Chip erase completed successfully in %.1fs' % (time.time() - t)
  1377. def erase_region(esp, args):
  1378. print 'Erasing region (may be slow depending on size)...'
  1379. t = time.time()
  1380. esp.erase_region(args.address, args.size)
  1381. print 'Erase completed successfully in %.1f seconds.' % (time.time() - t)
  1382. def run(esp, args):
  1383. esp.run()
  1384. def flash_id(esp, args):
  1385. flash_id = esp.flash_id()
  1386. print 'Manufacturer: %02x' % (flash_id & 0xff)
  1387. print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff)
  1388. def read_flash(esp, args):
  1389. if args.no_progress:
  1390. flash_progress = None
  1391. else:
  1392. def flash_progress(progress, length):
  1393. msg = '%d (%d %%)' % (progress, progress * 100.0 / length)
  1394. padding = '\b' * len(msg)
  1395. if progress == length:
  1396. padding = '\n'
  1397. sys.stdout.write(msg + padding)
  1398. sys.stdout.flush()
  1399. t = time.time()
  1400. data = esp.read_flash(args.address, args.size, flash_progress)
  1401. t = time.time() - t
  1402. print ('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  1403. % (len(data), args.address, t, len(data) / t * 8 / 1000))
  1404. file(args.filename, 'wb').write(data)
  1405. def verify_flash(esp, args, flash_params=None):
  1406. differences = False
  1407. for address, argfile in args.addr_filename:
  1408. image = argfile.read()
  1409. argfile.seek(0) # rewind in case we need it again
  1410. if address == 0 and image[0] == '\xe9' and flash_params is not None:
  1411. image = image[0:2] + flash_params + image[4:]
  1412. image_size = len(image)
  1413. print 'Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name)
  1414. # Try digest first, only read if there are differences.
  1415. digest = esp.flash_md5sum(address, image_size)
  1416. expected_digest = hashlib.md5(image).hexdigest()
  1417. if digest == expected_digest:
  1418. print '-- verify OK (digest matched)'
  1419. continue
  1420. else:
  1421. differences = True
  1422. if getattr(args, 'diff', 'no') != 'yes':
  1423. print '-- verify FAILED (digest mismatch)'
  1424. continue
  1425. flash = esp.read_flash(address, image_size)
  1426. assert flash != image
  1427. diff = [i for i in xrange(image_size) if flash[i] != image[i]]
  1428. print '-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0])
  1429. for d in diff:
  1430. print ' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d]))
  1431. if differences:
  1432. raise FatalError("Verify failed.")
  1433. def read_flash_status(esp, args):
  1434. print ('Status value: 0x%04x' % esp.read_status(args.bytes))
  1435. def write_flash_status(esp, args):
  1436. fmt = "0x%%0%dx" % (args.bytes * 2)
  1437. args.value = args.value & ((1 << (args.bytes * 8)) - 1)
  1438. print (('Initial flash status: ' + fmt) % esp.read_status(args.bytes))
  1439. print (('Setting flash status: ' + fmt) % args.value)
  1440. esp.write_status(args.value, args.bytes, args.non_volatile)
  1441. print (('After flash status: ' + fmt) % esp.read_status(args.bytes))
  1442. def version(args):
  1443. print __version__
  1444. #
  1445. # End of operations functions
  1446. #
  1447. def main():
  1448. parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
  1449. parser.add_argument('--chip', '-c',
  1450. help='Target chip type',
  1451. choices=['auto', 'esp8266', 'esp31', 'esp32'],
  1452. default=os.environ.get('ESPTOOL_CHIP', 'auto'))
  1453. parser.add_argument(
  1454. '--port', '-p',
  1455. help='Serial port device',
  1456. default=os.environ.get('ESPTOOL_PORT', ESPLoader.DEFAULT_PORT))
  1457. parser.add_argument(
  1458. '--baud', '-b',
  1459. help='Serial port baud rate used when flashing/reading',
  1460. type=arg_auto_int,
  1461. default=os.environ.get('ESPTOOL_BAUD', ESPLoader.ESP_ROM_BAUD))
  1462. parser.add_argument(
  1463. '--before',
  1464. help='What to do before connecting to the chip',
  1465. choices=['default_reset', 'no_reset', 'esp32r0'],
  1466. default=os.environ.get('ESPTOOL_BEFORE', 'default_reset'))
  1467. parser.add_argument(
  1468. '--after', '-a',
  1469. help='What to do after esptool.py is finished',
  1470. choices=['hard_reset', 'soft_reset', 'no_reset'],
  1471. default=os.environ.get('ESPTOOL_AFTER', 'hard_reset'))
  1472. parser.add_argument(
  1473. '--no-stub',
  1474. help="Disable launching the flasher stub, only talk to ROM bootloader. Some features will not be available.",
  1475. action='store_true')
  1476. subparsers = parser.add_subparsers(
  1477. dest='operation',
  1478. help='Run esptool {command} -h for additional help')
  1479. parser_load_ram = subparsers.add_parser(
  1480. 'load_ram',
  1481. help='Download an image to RAM and execute')
  1482. parser_load_ram.add_argument('filename', help='Firmware image')
  1483. parser_dump_mem = subparsers.add_parser(
  1484. 'dump_mem',
  1485. help='Dump arbitrary memory to disk')
  1486. parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
  1487. parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  1488. parser_dump_mem.add_argument('filename', help='Name of binary dump')
  1489. parser_read_mem = subparsers.add_parser(
  1490. 'read_mem',
  1491. help='Read arbitrary memory location')
  1492. parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
  1493. parser_write_mem = subparsers.add_parser(
  1494. 'write_mem',
  1495. help='Read-modify-write to arbitrary memory location')
  1496. parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
  1497. parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
  1498. parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int)
  1499. def add_spi_flash_subparsers(parent, auto_detect=False):
  1500. """ Add common parser arguments for SPI flash properties """
  1501. parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
  1502. choices=['40m', '26m', '20m', '80m'],
  1503. default=os.environ.get('ESPTOOL_FF', '40m'))
  1504. parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
  1505. choices=['qio', 'qout', 'dio', 'dout'],
  1506. default=os.environ.get('ESPTOOL_FM', 'qio'))
  1507. parent.add_argument('--flash_size', '-fs', help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16M)'
  1508. ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1, 4MB-2)',
  1509. action=FlashSizeAction, auto_detect=auto_detect,
  1510. default=os.environ.get('ESPTOOL_FS', 'detect' if auto_detect else '1MB'))
  1511. parent.add_argument('--ucIsHspi', '-ih', help='Config SPI PORT/PINS (Espressif internal feature)',action='store_true')
  1512. parent.add_argument('--ucIsLegacy', '-il', help='Config SPI LEGACY (Espressif internal feature)',action='store_true')
  1513. parser_write_flash = subparsers.add_parser(
  1514. 'write_flash',
  1515. help='Write a binary blob to flash')
  1516. parser_write_flash.add_argument('addr_filename', metavar='<address> <filename>', help='Address followed by binary filename, separated by space',
  1517. action=AddrFilenamePairAction)
  1518. add_spi_flash_subparsers(parser_write_flash, auto_detect=True)
  1519. parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  1520. parser_write_flash.add_argument('--verify', help='Verify just-written data (only necessary if very cautious, data is already CRCed', action='store_true')
  1521. parser_write_flash.add_argument('--compress', '-z', help='Compress data in transfer',action="store_true")
  1522. subparsers.add_parser(
  1523. 'run',
  1524. help='Run application code in flash')
  1525. parser_image_info = subparsers.add_parser(
  1526. 'image_info',
  1527. help='Dump headers from an application image')
  1528. parser_image_info.add_argument('filename', help='Image file to parse')
  1529. parser_make_image = subparsers.add_parser(
  1530. 'make_image',
  1531. help='Create an application image from binary files')
  1532. parser_make_image.add_argument('output', help='Output image file')
  1533. parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
  1534. parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
  1535. parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
  1536. parser_elf2image = subparsers.add_parser(
  1537. 'elf2image',
  1538. help='Create an application image from ELF file')
  1539. parser_elf2image.add_argument('input', help='Input ELF file')
  1540. parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
  1541. parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1')
  1542. parser_elf2image.add_argument('--set-encrypt-flag', help='Flag image to be encrypted by bootloader after flashing.', action="store_true")
  1543. add_spi_flash_subparsers(parser_elf2image)
  1544. subparsers.add_parser(
  1545. 'read_mac',
  1546. help='Read MAC address from OTP ROM')
  1547. subparsers.add_parser(
  1548. 'chip_id',
  1549. help='Read Chip ID from OTP ROM')
  1550. subparsers.add_parser(
  1551. 'flash_id',
  1552. help='Read SPI flash manufacturer and device ID')
  1553. parser_read_status = subparsers.add_parser(
  1554. 'read_flash_status',
  1555. help='Read SPI flash status register')
  1556. parser_read_status.add_argument('--bytes', help='Number of bytes to read (1-3)', type=int, choices=[1,2,3], default=2)
  1557. parser_write_status = subparsers.add_parser(
  1558. 'write_flash_status',
  1559. help='Write SPI flash status register')
  1560. parser_write_status.add_argument('--non-volatile', help='Write non-volatile bits (use with caution)', action='store_true')
  1561. parser_write_status.add_argument('--bytes', help='Number of status bytes to write (1-3)', type=int, choices=[1,2,3], default=2)
  1562. parser_write_status.add_argument('value', help='New value', type=arg_auto_int)
  1563. parser_read_flash = subparsers.add_parser(
  1564. 'read_flash',
  1565. help='Read SPI flash content')
  1566. parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
  1567. parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  1568. parser_read_flash.add_argument('filename', help='Name of binary dump')
  1569. parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  1570. parser_verify_flash = subparsers.add_parser(
  1571. 'verify_flash',
  1572. help='Verify a binary blob against flash')
  1573. parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
  1574. action=AddrFilenamePairAction)
  1575. parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
  1576. choices=['no', 'yes'], default='no')
  1577. subparsers.add_parser(
  1578. 'erase_flash',
  1579. help='Perform Chip Erase on SPI flash')
  1580. parser_erase_region = subparsers.add_parser(
  1581. 'erase_region',
  1582. help='Erase a region of the flash')
  1583. parser_erase_region.add_argument('address', help='Start address (must be multiple of 4096)', type=arg_auto_int)
  1584. parser_erase_region.add_argument('size', help='Size of region to erase (must be multiple of 4096)', type=arg_auto_int)
  1585. subparsers.add_parser(
  1586. 'version', help='Print esptool version')
  1587. # internal sanity check - every operation matches a module function of the same name
  1588. for operation in subparsers.choices.keys():
  1589. assert operation in globals(), "%s should be a module function" % operation
  1590. expand_file_arguments()
  1591. args = parser.parse_args()
  1592. print 'esptool.py v%s' % __version__
  1593. # operation function can take 1 arg (args), 2 args (esp, arg)
  1594. # or be a member function of the ESPLoader class.
  1595. operation_func = globals()[args.operation]
  1596. operation_args,_,_,_ = inspect.getargspec(operation_func)
  1597. if operation_args[0] == 'esp': # operation function takes an ESPLoader connection object
  1598. initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
  1599. if args.chip == 'auto':
  1600. esp = ESPLoader.detect_chip(args.port, initial_baud, args.before)
  1601. else:
  1602. chip_class = {
  1603. 'esp8266': ESP8266ROM,
  1604. 'esp32': ESP32ROM,
  1605. }[args.chip]
  1606. esp = chip_class(args.port, initial_baud)
  1607. esp.connect(args.before)
  1608. if not args.no_stub:
  1609. esp = esp.run_stub()
  1610. if args.baud > initial_baud:
  1611. try:
  1612. esp.change_baud(args.baud)
  1613. except NotImplementedInROMError:
  1614. print "WARNING: ROM doesn't support changing baud rate. Keeping initial baud rate %d" % initial_baud
  1615. # override common SPI flash parameter stuff as required
  1616. if hasattr(args, "ucIsHspi"):
  1617. print "Attaching SPI flash..."
  1618. esp.flash_spi_attach(args.ucIsHspi,args.ucIsLegacy)
  1619. else:
  1620. esp.flash_spi_attach(0, 0)
  1621. if hasattr(args, "flash_size"):
  1622. print "Configuring flash size..."
  1623. detect_flash_size(esp, args)
  1624. esp.flash_set_parameters(flash_size_bytes(args.flash_size))
  1625. operation_func(esp, args)
  1626. # finish execution based on args.after
  1627. if args.after == 'hard_reset':
  1628. print 'Hard resetting...'
  1629. esp.hard_reset()
  1630. elif args.after == 'soft_reset':
  1631. print 'Soft resetting...'
  1632. # flash_finish will trigger a soft reset
  1633. esp.soft_reset(False)
  1634. else:
  1635. print 'Staying in bootloader.'
  1636. if esp.IS_STUB:
  1637. esp.soft_reset(True) # exit stub back to ROM loader
  1638. else:
  1639. operation_func(args)
  1640. def expand_file_arguments():
  1641. """ Any argument starting with "@" gets replaced with all values read from a text file.
  1642. Text file arguments can be split by newline or by space.
  1643. Values are added "as-is", as if they were specified in this order on the command line.
  1644. """
  1645. new_args = []
  1646. expanded = False
  1647. for arg in sys.argv:
  1648. if arg.startswith("@"):
  1649. expanded = True
  1650. with open(arg[1:],"r") as f:
  1651. for line in f.readlines():
  1652. new_args += shlex.split(line)
  1653. else:
  1654. new_args.append(arg)
  1655. if expanded:
  1656. print "esptool.py %s" % (" ".join(new_args[1:]))
  1657. sys.argv = new_args
  1658. class FlashSizeAction(argparse.Action):
  1659. """ Custom flash size parser class to support backwards compatibility with megabit size arguments.
  1660. (At next major relase, remove deprecated sizes and this can become a 'normal' choices= argument again.)
  1661. """
  1662. def __init__(self, option_strings, dest, nargs=1, auto_detect=False, **kwargs):
  1663. super(FlashSizeAction, self).__init__(option_strings, dest, nargs, **kwargs)
  1664. self._auto_detect = auto_detect
  1665. def __call__(self, parser, namespace, values, option_string=None):
  1666. try:
  1667. value = {
  1668. '2m': '256KB',
  1669. '4m': '512KB',
  1670. '8m': '1MB',
  1671. '16m': '2MB',
  1672. '32m': '4MB',
  1673. '16m-c1': '2MB-c1',
  1674. '32m-c1': '4MB-c1',
  1675. '32m-c2': '4MB-c2'
  1676. }[values[0]]
  1677. print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
  1678. print("Please use the equivalent size '%s'." % (value))
  1679. print("Megabit arguments may be removed in a future release.")
  1680. except KeyError:
  1681. value = values[0]
  1682. known_sizes = dict(ESP8266ROM.FLASH_SIZES)
  1683. known_sizes.update(ESP32ROM.FLASH_SIZES)
  1684. if self._auto_detect:
  1685. known_sizes['detect'] = 'detect'
  1686. if value not in known_sizes:
  1687. raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
  1688. setattr(namespace, self.dest, value)
  1689. class AddrFilenamePairAction(argparse.Action):
  1690. """ Custom parser class for the address/filename pairs passed as arguments """
  1691. def __init__(self, option_strings, dest, nargs='+', **kwargs):
  1692. super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
  1693. def __call__(self, parser, namespace, values, option_string=None):
  1694. # validate pair arguments
  1695. pairs = []
  1696. for i in range(0,len(values),2):
  1697. try:
  1698. address = int(values[i],0)
  1699. except ValueError as e:
  1700. raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
  1701. try:
  1702. argfile = open(values[i + 1], 'rb')
  1703. except IOError as e:
  1704. raise argparse.ArgumentError(self, e)
  1705. except IndexError:
  1706. raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
  1707. pairs.append((address, argfile))
  1708. setattr(namespace, self.dest, pairs)
  1709. # Binary stub code (see flasher_stub dir for source & details)
  1710. ESP8266ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b"""
  1711. eNrNPWtj00a2f8VSQkhMaDWSrEcIxX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oyFlymHllGjFDRASElqfl9zjwI3ew6MSnkhdkkfAyvpmekpgYCga4HQAFpbAW+2Myuw0EMK5ojmAJlq7KOgl0X\
  1804. X4CKIcXImMmkUk5NuwVfTQJ/kf2XqQXEsJ156Z/Ir0UBZGw3DonzAxi4SUtj1EQuI4ltty0HpNNjHvgyTAqoIuUBULjJR84Pf4byFxVDmCaZ/M9oaomfHVy635mDUuYJTI1lIrj4GQx/IllM06+l4kiTIwhdp1Fh\
  1805. 4YY9yPW6wBu9ZNsxr64TdrhM/waN8SA8ARt/8Pi1z5npdy838smjjRkgFl5xF/ye9EJM1reC4Gb+HmYX3wRdQJEBjr1k74m//PphCCZJoAgoQYaf9g0zZ64r46fTUn5tBBiT3ZL705TbDCRmG0rhs3n/I5NcZfwx\
  1806. W+1ukrWUZhMmTvbYEnKGkXiAk66EkbR70XXvUyWimOxAFEUSJ2F1GnBL0YEedvYnO7Vd2X/9sbKX8AMxrYpsNsszY/gN/WhMiqjQH35KFvefZpnOp9C/Wa4ub7rGTOXTv/4HMdHC5A==\
  1807. """)))
  1808. if __name__ == '__main__':
  1809. try:
  1810. main()
  1811. except FatalError as e:
  1812. print '\nA fatal error occurred: %s' % e
  1813. sys.exit(2)