esptool.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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/themadinventor/esptool/issues/21
  3. #
  4. # ESP8266 ROM Bootloader Utility
  5. # https://github.com/themadinventor/esptool
  6. #
  7. # Copyright (C) 2014-2016 Fredrik Ahlberg, Angus Gratton, other contributors as noted.
  8. # ESP31/32 support Copyright (C) 2016 Angus Gratton, based in part on work Copyright
  9. # (C) 2015-2016 Espressif Systems.
  10. #
  11. # This program is free software; you can redistribute it and/or modify it under
  12. # the terms of the GNU General Public License as published by the Free Software
  13. # Foundation; either version 2 of the License, or (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful, but WITHOUT
  16. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  17. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along with
  20. # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  21. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. import argparse
  23. import hashlib
  24. import inspect
  25. import json
  26. import os
  27. import serial
  28. import struct
  29. import subprocess
  30. import sys
  31. import time
  32. import zlib
  33. __version__ = "2.0-dev"
  34. MAX_UINT32 = 0xffffffff
  35. MAX_UINT24 = 0xffffff
  36. class ESPROM(object):
  37. """ Base class providing access to ESP ROM bootloader. Subclasses provide
  38. ESP8266, ESP31 & ESP32 specific functionality.
  39. Don't instantiate this base class directly, either instantiate a subclass or
  40. call ESPROM.detect_chip() which will interrogate the chip and return the
  41. appropriate subclass instance.
  42. """
  43. CHIP_NAME = "Espressif device"
  44. DEFAULT_PORT = "/dev/ttyUSB0"
  45. # These are the currently known commands supported by the ROM
  46. ESP_FLASH_BEGIN = 0x02
  47. ESP_FLASH_DATA = 0x03
  48. ESP_FLASH_END = 0x04
  49. ESP_MEM_BEGIN = 0x05
  50. ESP_MEM_END = 0x06
  51. ESP_MEM_DATA = 0x07
  52. ESP_SYNC = 0x08
  53. ESP_WRITE_REG = 0x09
  54. ESP_READ_REG = 0x0a
  55. # Maximum block sized for RAM and Flash writes, respectively.
  56. ESP_RAM_BLOCK = 0x1800
  57. ESP_FLASH_BLOCK = 0x400
  58. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  59. ESP_ROM_BAUD = 115200
  60. # First byte of the application image
  61. ESP_IMAGE_MAGIC = 0xe9
  62. # Initial state for the checksum routine
  63. ESP_CHECKSUM_MAGIC = 0xef
  64. # Flash sector size, minimum unit of erase.
  65. ESP_FLASH_SECTOR = 0x1000
  66. UART_DATA_REG_ADDR = 0x60000078
  67. # SPI peripheral "command" bitmasks
  68. SPI_CMD_READ_ID = 0x10000000
  69. # Memory addresses
  70. IROM_MAP_START = 0x40200000
  71. IROM_MAP_END = 0x40300000
  72. # The number of bytes in the response that signify command status
  73. STATUS_BYTES_LENGTH = 2
  74. def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, do_connect=True):
  75. """Base constructor for ESPROM objects
  76. Don't call this constructor, either instantiate ESP8266ROM,
  77. ESP31ROM, or ESP32ROM, or use ESPROM.detect_chip().
  78. """
  79. self._port = serial.Serial(port)
  80. self._slip_reader = slip_reader(self._port)
  81. # setting baud rate in a separate step is a workaround for
  82. # CH341 driver on some Linux versions (this opens at 9600 then
  83. # sets), shouldn't matter for other platforms/drivers. See
  84. # https://github.com/themadinventor/esptool/issues/44#issuecomment-107094446
  85. self._port.baudrate = baud
  86. if do_connect:
  87. self.connect()
  88. @staticmethod
  89. def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD):
  90. """Use serial access to detect the chip type.
  91. We use the UART's datecode register for this, it's mapped at
  92. the same address on ESP8266 & ESP31/32 so we can use one
  93. memory read and compare to the datecode register for each chip
  94. type.
  95. """
  96. detect_port = ESPROM(port, baud, True)
  97. sys.stdout.write('Detecting chip type... ')
  98. date_reg = detect_port.read_reg(ESPROM.UART_DATA_REG_ADDR)
  99. for cls in [ESP8266ROM, ESP31ROM, ESP32ROM]:
  100. if date_reg == cls.DATE_REG_VALUE:
  101. inst = cls(port, baud, False) # don't connect a second time
  102. print '%s' % inst.CHIP_NAME
  103. return inst
  104. print ''
  105. raise FatalError("Unexpected UART datecode value 0x%08x. Failed to autodetect chip type." % date_reg)
  106. """ Read a SLIP packet from the serial port """
  107. def read(self):
  108. return self._slip_reader.next()
  109. """ Write bytes to the serial port while performing SLIP escaping """
  110. def write(self, packet):
  111. buf = '\xc0' \
  112. + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \
  113. + '\xc0'
  114. self._port.write(buf)
  115. """ Calculate checksum of a blob, as it is defined by the ROM """
  116. @staticmethod
  117. def checksum(data, state=ESP_CHECKSUM_MAGIC):
  118. for b in data:
  119. state ^= ord(b)
  120. return state
  121. """ Send a request and read the response """
  122. def command(self, op=None, data=None, chk=0):
  123. if op is not None:
  124. pkt = struct.pack('<BBHI', 0x00, op, len(data), chk) + data
  125. self.write(pkt)
  126. # tries to get a response until that response has the
  127. # same operation as the request or a retries limit has
  128. # exceeded. This is needed for some esp8266s that
  129. # reply with more sync responses than expected.
  130. for retry in xrange(100):
  131. p = self.read()
  132. if len(p) < 8:
  133. continue
  134. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
  135. if resp != 1:
  136. continue
  137. data = p[8:]
  138. if op is None or op_ret == op:
  139. return val, data
  140. raise FatalError("Response doesn't match request")
  141. def check_command(self, op_description, op=None, data=None, chk=0):
  142. """
  143. Execute a command with 'command', check the result code and throw an appropriate
  144. FatalError if it fails.
  145. Returns the "result" of a successful command.
  146. """
  147. val, data = self.command(op, data, chk)
  148. # things are a bit weird here, bear with us
  149. # the status bytes are the last 2/4 bytes in the data (depending on chip)
  150. if len(data) < self.STATUS_BYTES_LENGTH:
  151. raise FatalError("Failed to %s. Only got %d byte status response." % op_description, len(data))
  152. status_bytes = data[-self.STATUS_BYTES_LENGTH:]
  153. # we only care if the first one is non-zero. If it is, the second byte is a reason.
  154. if status_bytes[0] != '\0':
  155. raise FatalError.WithResult('Failed to %s' % op_description, status_bytes)
  156. # if we had more data than just the status bytes, return it as the result
  157. # (this is used by the md5sum command, maybe other commands?)
  158. if len(data) > self.STATUS_BYTES_LENGTH:
  159. return data[:-self.STATUS_BYTES_LENGTH]
  160. else: # otherwise, just return the 'val' field which comes from the reply header (this is used by read_reg)
  161. return val
  162. def flush_input(self):
  163. self._port.flushInput()
  164. self._slip_reader = slip_reader(self._port)
  165. def sync(self):
  166. """ Perform a connection test """
  167. self.command(ESPROM.ESP_SYNC, '\x07\x07\x12\x20' + 32 * '\x55')
  168. for i in xrange(7):
  169. self.command()
  170. def connect(self):
  171. """ Try connecting repeatedly until successful, or giving up """
  172. print 'Connecting...'
  173. for _ in xrange(4):
  174. # issue reset-to-bootloader:
  175. # RTS = either CH_PD or nRESET (both active low = chip in reset)
  176. # DTR = GPIO0 (active low = boot to flasher)
  177. self._port.setDTR(False)
  178. self._port.setRTS(True)
  179. time.sleep(0.05)
  180. self._port.setDTR(True)
  181. self._port.setRTS(False)
  182. time.sleep(0.05)
  183. self._port.setDTR(False)
  184. # worst-case latency timer should be 255ms (probably <20ms)
  185. self._port.timeout = 0.3
  186. last_exception = None
  187. for _ in xrange(4):
  188. try:
  189. self.flush_input()
  190. self._port.flushOutput()
  191. self.sync()
  192. self._port.timeout = 5
  193. return
  194. except FatalError as e:
  195. last_exception = e
  196. time.sleep(0.05)
  197. raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_exception))
  198. """ Read memory address in target """
  199. def read_reg(self, addr):
  200. # we don't call check_command here because read_reg() function is called
  201. # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
  202. # for different chip types (!)
  203. val, data = self.command(ESPROM.ESP_READ_REG, struct.pack('<I', addr))
  204. if data[0] != '\0':
  205. raise FatalError.WithResult("Failed to read register address %08x" % addr, data)
  206. return val
  207. """ Write to memory address in target """
  208. def write_reg(self, addr, value, mask, delay_us=0):
  209. return self.check_command("write target memory", ESPROM.ESP_WRITE_REG,
  210. struct.pack('<IIII', addr, value, mask, delay_us))
  211. """ Start downloading an application image to RAM """
  212. def mem_begin(self, size, blocks, blocksize, offset):
  213. return self.check_command("enter RAM download mode", ESPROM.ESP_MEM_BEGIN,
  214. struct.pack('<IIII', size, blocks, blocksize, offset))
  215. """ Send a block of an image to RAM """
  216. def mem_block(self, data, seq):
  217. return self.check_command("write to target RAM", ESPROM.ESP_MEM_DATA,
  218. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  219. ESPROM.checksum(data))
  220. """ Leave download mode and run the application """
  221. def mem_finish(self, entrypoint=0):
  222. return self.check_command("leave RAM download mode", ESPROM.ESP_MEM_END,
  223. struct.pack('<II', int(entrypoint == 0), entrypoint))
  224. """ Start downloading to Flash (performs an erase) """
  225. def flash_begin(self, size, offset):
  226. old_tmo = self._port.timeout
  227. num_blocks = (size + ESPROM.ESP_FLASH_BLOCK - 1) / ESPROM.ESP_FLASH_BLOCK
  228. erase_size = self.get_erase_size(size)
  229. self._port.timeout = 20
  230. t = time.time()
  231. self.check_command("enter Flash download mode", ESPROM.ESP_FLASH_BEGIN,
  232. struct.pack('<IIII', erase_size, num_blocks, ESPROM.ESP_FLASH_BLOCK, offset))
  233. if size != 0:
  234. print "Took %.2fs to erase flash block" % (time.time() - t)
  235. self._port.timeout = old_tmo
  236. """ Write block to flash """
  237. def flash_block(self, data, seq):
  238. self.check_command("write to target Flash after seq %d" % seq,
  239. ESPROM.ESP_FLASH_DATA,
  240. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  241. ESPROM.checksum(data))
  242. """ Leave flash mode and run/reboot """
  243. def flash_finish(self, reboot=False):
  244. pkt = struct.pack('<I', int(not reboot))
  245. self.check_command("leave Flash mode", ESPROM.ESP_FLASH_END, pkt)
  246. """ Run application code in flash """
  247. def run(self, reboot=False):
  248. # Fake flash begin immediately followed by flash end
  249. self.flash_begin(0, 0)
  250. self.flash_finish(reboot)
  251. """ Read SPI flash manufacturer and device id """
  252. def flash_id(self):
  253. self.flash_begin(0, 0)
  254. self.write_reg(self.SPI_W0_REG_ADDR, 0x0, MAX_UINT32)
  255. self.write_reg(self.SPI_CMD_REG_ADDR, self.SPI_CMD_READ_ID, MAX_UINT32)
  256. flash_id = self.read_reg(self.SPI_W0_REG_ADDR)
  257. self.flash_finish(False)
  258. return flash_id
  259. def parse_flash_size_arg(self, arg):
  260. try:
  261. return self.FLASH_SIZES[arg]
  262. except KeyError:
  263. raise FatalError("Flash size '%s' is not supported by this chip type. Supported sizes: %s"
  264. % (arg, ", ".join(self.FLASH_SIZES.keys())))
  265. """ Abuse the loader protocol to force flash to be left in write mode """
  266. def flash_unlock_dio(self):
  267. # Enable flash write mode
  268. self.flash_begin(0, 0)
  269. # Reset the chip rather than call flash_finish(), which would have
  270. # write protected the chip again (why oh why does it do that?!)
  271. self.mem_begin(0,0,0,0x40100000)
  272. self.mem_finish(0x40000080)
  273. def run_stub(self, stub, params, read_output=False):
  274. stub = dict(stub)
  275. stub['code'] = unhexify(stub['code'])
  276. if 'data' in stub:
  277. stub['data'] = unhexify(stub['data'])
  278. if stub['num_params'] != len(params):
  279. raise FatalError('Stub requires %d params, %d provided'
  280. % (stub['num_params'], len(params)))
  281. params = struct.pack('<' + ('I' * stub['num_params']), *params)
  282. pc = params + stub['code']
  283. # Upload
  284. self.mem_begin(len(pc), 1, len(pc), stub['params_start'])
  285. self.mem_block(pc, 0)
  286. if 'data' in stub:
  287. self.mem_begin(len(stub['data']), 1, len(stub['data']), stub['data_start'])
  288. self.mem_block(stub['data'], 0)
  289. self.mem_finish(stub['entry'])
  290. if read_output:
  291. print 'Stub executed, reading response:'
  292. while True:
  293. p = self.read()
  294. print hexify(p)
  295. if p == '':
  296. return
  297. class ESP8266ROM(ESPROM):
  298. """ Access class for ESP8266 ROM bootloader
  299. """
  300. CHIP_NAME = "ESP8266EX"
  301. DATE_REG_VALUE = 0x00062000
  302. # OTP ROM addresses
  303. ESP_OTP_MAC0 = 0x3ff00050
  304. ESP_OTP_MAC1 = 0x3ff00054
  305. ESP_OTP_MAC3 = 0x3ff0005c
  306. SPI_CMD_REG_ADDR = 0x60000200
  307. SPI_W0_REG_ADDR = 0x60000240
  308. FLASH_SIZES = {
  309. '512KB':0x00,
  310. '256KB':0x10,
  311. '1MB':0x20,
  312. '2MB':0x30,
  313. '4MB':0x40,
  314. '2MB-c1': 0x50,
  315. '4MB-c1':0x60,
  316. '4MB-c2':0x70}
  317. def change_baud(self, baud):
  318. pass # no change baud command on ESP8266 ROM
  319. def chip_id(self):
  320. """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """
  321. id0 = self.read_reg(self.ESP_OTP_MAC0)
  322. id1 = self.read_reg(self.ESP_OTP_MAC1)
  323. return (id0 >> 24) | ((id1 & MAX_UINT24) << 8)
  324. def read_mac(self):
  325. """ Read MAC from OTP ROM """
  326. mac0 = self.read_reg(self.ESP_OTP_MAC0)
  327. mac1 = self.read_reg(self.ESP_OTP_MAC1)
  328. mac3 = self.read_reg(self.ESP_OTP_MAC3)
  329. if (mac3 != 0):
  330. oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
  331. elif ((mac1 >> 16) & 0xff) == 0:
  332. oui = (0x18, 0xfe, 0x34)
  333. elif ((mac1 >> 16) & 0xff) == 1:
  334. oui = (0xac, 0xd0, 0x74)
  335. else:
  336. raise FatalError("Unknown OUI")
  337. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  338. def get_erase_size(self, size):
  339. """ Calculate an erase size given a specific size in bytes.
  340. Provides a workaround for the bootloader erase bug."""
  341. sectors_per_block = 16
  342. sector_size = self.ESP_FLASH_SECTOR
  343. num_sectors = (size + sector_size - 1) / sector_size
  344. start_sector = offset / sector_size
  345. head_sectors = sectors_per_block - (start_sector % sectors_per_block)
  346. if num_sectors < head_sectors:
  347. head_sectors = num_sectors
  348. if num_sectors < 2 * head_sectors:
  349. return (num_sectors + 1) / 2 * sector_size
  350. else:
  351. return (num_sectors - head_sectors) * sector_size
  352. class ESP31ROM(ESPROM):
  353. """ Access class for ESP31 ROM bootloader
  354. """
  355. CHIP_NAME = "ESP31"
  356. DATE_REG_VALUE = 0x15052100
  357. SPI_CMD_REG_ADDR = 0x60003000
  358. SPI_W0_REG_ADDR = 0x60003040
  359. EFUSE_BASE = 0x6001a000
  360. FLASH_SIZES = {
  361. '1MB':0x00,
  362. '2MB':0x10,
  363. '4MB':0x20,
  364. '8MB':0x30,
  365. '16MB':0x40
  366. }
  367. def read_efuse(self, n):
  368. """ Read the nth word of the ESP3x EFUSE region. """
  369. return self.read_reg(self.EFUSE_BASE + (4 * n))
  370. def chip_id(self):
  371. word16 = self.read_efuse(16)
  372. word17 = self.read_efuse(17)
  373. return ((word17 & MAX_UINT24) << 24) | (word16 >> 8) & MAX_UINT24
  374. def read_mac(self):
  375. """ Read MAC from EFUSE region """
  376. word16 = self.read_efuse(16)
  377. word17 = self.read_efuse(17)
  378. word18 = self.read_efuse(18)
  379. word19 = self.read_efuse(19)
  380. wifi_mac = (((word17 >> 16) & 0xff), ((word17 >> 8) & 0xff), ((word17 >> 0) & 0xff),
  381. ((word16 >> 24) & 0xff), ((word16 >> 16) & 0xff), ((word16 >> 8) & 0xff))
  382. bt_mac = (((word19 >> 16) & 0xff), ((word19 >> 8) & 0xff), ((word19 >> 0) & 0xff),
  383. ((word18 >> 24) & 0xff), ((word18 >> 16) & 0xff), ((word18 >> 8) & 0xff))
  384. return (wifi_mac,bt_mac)
  385. def get_erase_size(self, size):
  386. return size
  387. class ESP32ROM(ESP31ROM):
  388. """Access class for ESP32 ROM bootloader
  389. """
  390. CHIP_NAME = "ESP32"
  391. DATE_REG_VALUE = 0x15122500
  392. # ESP32-only commands
  393. ESP_SPI_FLASH_SET = 0xb
  394. ESP_SPI_ATTACH_REQ = 0xD
  395. ESP_CHANGE_BAUDRATE = 0x0F
  396. ESP_FLASH_DEFL_BEGIN = 0x10
  397. ESP_FLASH_DEFL_DATA = 0x11
  398. ESP_FLASH_DEFL_END = 0x12
  399. ESP_SPI_FLASH_MD5 = 0x13
  400. IROM_MAP_START = 0x400d0000
  401. IROM_MAP_END = 0x40400000
  402. DROM_MAP_START = 0x3F400000
  403. DROM_MAP_END = 0x3F700000
  404. # ESP32 uses a 4 byte status reply
  405. STATUS_BYTES_LENGTH = 4
  406. def flash_defl_begin(self, size, compsize, offset):
  407. """ Start downloading compressed data to Flash (performs an erase) """
  408. old_tmo = self._port.timeout
  409. num_blocks = (compsize + self.ESP_FLASH_BLOCK - 1) / self.ESP_FLASH_BLOCK
  410. erase_blocks = (size + self.ESP_FLASH_BLOCK - 1) / self.ESP_FLASH_BLOCK
  411. erase_size = size
  412. if erase_size > 0 and (offset + erase_size) >= (16 / 8) * 1024 * 1024:
  413. self.flash_spi_param_set()
  414. self._port.timeout = 20
  415. t = time.time()
  416. print "Unc size %d comp size %d comp blocks %d" % (size, compsize, num_blocks)
  417. self.check_command("enter compressed flash mode", self.ESP_FLASH_DEFL_BEGIN,
  418. struct.pack('<IIII', erase_blocks * self.ESP_FLASH_BLOCK, num_blocks, self.ESP_FLASH_BLOCK, offset))
  419. if size != 0:
  420. print "Took %.2fs to erase flash block" % (time.time() - t)
  421. self._port.timeout = old_tmo
  422. """ Write block to flash, send compressed """
  423. def flash_defl_block(self, data, seq):
  424. self.check_command("write compressed data to flash after seq %d" % seq,
  425. self.ESP_FLASH_DEFL_DATA, struct.pack('<IIII', len(data), seq, 0, 0) + data, ESPROM.checksum(data))
  426. """ Leave compressed flash mode and run/reboot """
  427. def flash_defl_finish(self, reboot=False):
  428. pkt = struct.pack('<I', int(not reboot))
  429. self.check_command("leave compressed flash mode", self.ESP_FLASH_DEFL_END, pkt)
  430. self.in_bootloader = False
  431. def flash_md5sum(self, addr, size):
  432. # the MD5 command is special (
  433. return self.check_command('calculate md5sum', self.ESP_SPI_FLASH_MD5, struct.pack('<IIII', addr, size, 0, 0))
  434. def change_baud(self, baud):
  435. print "Changing baud rate to %d" % baud
  436. self.command(self.ESP_CHANGE_BAUDRATE, struct.pack('<II', baud, 0))
  437. print "Changed."
  438. self._port.baudrate = baud
  439. time.sleep(0.05) # get rid of crap sent during baud rate change
  440. self.flush_input()
  441. def flash_spi_attach_req(self,ucIsHspi,ucIsLegacy):
  442. """Send SPI attach command
  443. Internal Espressif function. Deprecate?
  444. """
  445. print "SEND ESP SPI ATTACH CMD"
  446. # last 3 bytes in ESP_SPI_ATTACH_REQ argument are reserved values
  447. arg = struct.pack('<IBBBB', ucIsHspi, ucIsLegacy, 0, 0, 0)
  448. self.check_command("configure SPI Flash attachment", ESP32ROM.ESP_SPI_ATTACH_REQ,
  449. arg)
  450. def flash_spi_param_set(self):
  451. """Set the flash params for ESP booter
  452. I think this means writing a "flash_chip" type structure to RAM, so the ESP32 knows we have a larger flash size.
  453. """
  454. # FOR ESP32, SET FLASH INFO FOR ROM CODE, DEFAULT IS 16Mbits, WE NEED TO RE-SET IT TO A BIGGER SIZE.
  455. print("SET FLASH PARAMS")
  456. fl_id = 0
  457. total_size = (128 / 8) * 1024 * 1024
  458. block_size = 64 * 1024
  459. sector_size = 4 * 1024
  460. page_size = 256
  461. status_mask = 0xffff
  462. err = self.command(ESP32ROM.ESP_SPI_FLASH_SET,
  463. struct.pack('<IIIIII', fl_id, total_size, block_size, sector_size, page_size, status_mask))[1]
  464. if err: # Should be checking one part of this tuple or the other, I think
  465. raise FatalError.WithResult('Failed to config flash', err)
  466. class ESPBOOTLOADER(object):
  467. """ These are constants related to software ESP bootloader, working with 'v2' image files """
  468. # First byte of the "v2" application image
  469. IMAGE_V2_MAGIC = 0xea
  470. # First 'segment' value in a "v2" application image, appears to be a constant version value?
  471. IMAGE_V2_SEGMENT = 4
  472. def LoadFirmwareImage(chip, filename):
  473. """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
  474. original ROM firmware images (ESPFirmwareImage) or "v2" OTA bootloader images.
  475. Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2).
  476. """
  477. with open(filename, 'rb') as f:
  478. if chip == 'esp32':
  479. return ESP32FirmwareImage(f)
  480. else: # Otherwise, ESP8266 so look at magic to determine the image type
  481. magic = ord(f.read(1))
  482. f.seek(0)
  483. if magic == ESPROM.ESP_IMAGE_MAGIC:
  484. return ESPFirmwareImage(f)
  485. elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
  486. return OTAFirmwareImage(f)
  487. else:
  488. raise FatalError("Invalid image magic number: %d" % magic)
  489. class ImageSegment(object):
  490. """ Wrapper class for a segment in an ESP image
  491. (very similar to a section in an ELFImage also) """
  492. def __init__(self, addr, data, file_offs=None):
  493. self.addr = addr
  494. # pad all ImageSegments to at least 4 bytes length
  495. pad_mod = len(data) % 4
  496. if pad_mod != 0:
  497. data += "\x00" * (4 - pad_mod)
  498. self.data = data
  499. self.file_offs = file_offs
  500. def copy_with_new_addr(self, new_addr):
  501. """ Return a new ImageSegment with same data, but mapped at
  502. a new address. """
  503. return ImageSegment(new_addr, self.data, 0)
  504. def __repr__(self):
  505. r = "len 0x%05x load 0x%08x" % (len(self.data), self.addr)
  506. if self.file_offs is not None:
  507. r += " file_offs 0x%08x" % (self.file_offs)
  508. return r
  509. class ELFSection(ImageSegment):
  510. """ Wrapper class for a section in an ELF image, has a section
  511. name as well as the common properties of an ImageSegment. """
  512. def __init__(self, name, addr, data):
  513. super(ELFSection, self).__init__(addr, data)
  514. self.name = name
  515. def __repr__(self):
  516. return "%s %s" % (self.name, super(ELFSection, self).__repr__())
  517. class BaseFirmwareImage(object):
  518. SEG_HEADER_LEN = 8
  519. """ Base class with common firmware image functions """
  520. def __init__(self):
  521. self.segments = []
  522. self.entrypoint = 0
  523. def load_common_header(self, load_file, expected_magic):
  524. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  525. if magic != expected_magic or segments > 16:
  526. raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
  527. return segments
  528. def load_segment(self, f, is_irom_segment=False):
  529. """ Load the next segment from the image file """
  530. file_offs = f.tell()
  531. (offset, size) = struct.unpack('<II', f.read(8))
  532. if not is_irom_segment:
  533. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  534. print('WARNING: Suspicious segment 0x%x, length %d' % (offset, size))
  535. segment_data = f.read(size)
  536. if len(segment_data) < size:
  537. raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
  538. segment = ImageSegment(offset, segment_data, file_offs)
  539. self.segments.append(segment)
  540. return segment
  541. def save_segment(self, f, segment, checksum=None):
  542. """ Save the next segment to the image file, return next checksum value if provided """
  543. f.write(struct.pack('<II', segment.addr, len(segment.data)))
  544. f.write(segment.data)
  545. if checksum is not None:
  546. return ESPROM.checksum(segment.data, checksum)
  547. def read_checksum(self, f):
  548. """ Return ESPROM checksum from end of just-read image """
  549. # Skip the padding. The checksum is stored in the last byte so that the
  550. # file is a multiple of 16 bytes.
  551. align_file_position(f, 16)
  552. return ord(f.read(1))
  553. def append_checksum(self, f, checksum):
  554. """ Append ESPROM checksum to the just-written image """
  555. align_file_position(f, 16)
  556. f.write(struct.pack('B', checksum))
  557. def write_common_header(self, f, segments):
  558. f.write(struct.pack('<BBBBI', ESPROM.ESP_IMAGE_MAGIC, len(segments),
  559. self.flash_mode, self.flash_size_freq, self.entrypoint))
  560. def is_irom_addr(self, addr):
  561. """ Returns True if an address starts in the irom region.
  562. Valid for ESP8266 only.
  563. """
  564. return ESPROM.IROM_MAP_START <= addr < ESPROM.IROM_MAP_END
  565. def get_irom_segment(self):
  566. irom_segments = [s for s in self.segments if self.is_irom_addr(s.addr)]
  567. if len(irom_segments) > 0:
  568. if len(irom_segments) != 1:
  569. raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
  570. return irom_segments[0]
  571. return None
  572. def get_non_irom_segments(self):
  573. irom_segment = self.get_irom_segment()
  574. return [s for s in self.segments if s != irom_segment]
  575. class ESPFirmwareImage(BaseFirmwareImage):
  576. """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
  577. def __init__(self, load_file=None):
  578. super(ESPFirmwareImage, self).__init__()
  579. self.flash_mode = 0
  580. self.flash_size_freq = 0
  581. self.version = 1
  582. if load_file is not None:
  583. segments = self.load_common_header(load_file, ESPROM.ESP_IMAGE_MAGIC)
  584. for _ in xrange(segments):
  585. self.load_segment(load_file)
  586. self.checksum = self.read_checksum(load_file)
  587. def default_output_name(self, input_file):
  588. """ Derive a default output name from the ELF name. """
  589. return input_file + '-'
  590. def save(self, basename):
  591. """ Save a set of V1 images for flashing. Parameter is a base filename. """
  592. # IROM data goes in its own plain binary file
  593. irom_segment = self.get_irom_segment()
  594. if irom_segment is not None:
  595. with open("%s0x%05x.bin" % (basename, irom_segment.addr), "wb") as f:
  596. f.write(irom_segment.data)
  597. # everything but IROM goes at 0x00000 in an image file
  598. normal_segments = self.get_non_irom_segments()
  599. with open("%s0x00000.bin" % basename, 'wb') as f:
  600. self.write_common_header(f, normal_segments)
  601. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  602. for segment in self.segments:
  603. checksum = self.save_segment(f, segment, checksum)
  604. self.append_checksum(f, checksum)
  605. class OTAFirmwareImage(BaseFirmwareImage):
  606. """ 'Version 2' firmware image, segments loaded by software bootloader stub
  607. (ie Espressif bootloader or rboot)
  608. """
  609. def __init__(self, load_file=None):
  610. super(OTAFirmwareImage, self).__init__()
  611. self.version = 2
  612. if load_file is not None:
  613. segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC)
  614. if segments != ESPBOOTLOADER.IMAGE_V2_SEGMENT:
  615. # segment count is not really segment count here, but we expect to see '4'
  616. print 'Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments
  617. # irom segment comes before the second header
  618. #
  619. # the file is saved in the image with a zero load address
  620. # in the header, so we need to calculate a load address
  621. irom_offs = load_file.tell()
  622. irom_segment = self.load_segment(load_file, True)
  623. irom_segment.addr = irom_offs + ESPROM.IROM_MAP_START
  624. first_flash_mode = self.flash_mode
  625. first_flash_size_freq = self.flash_size_freq
  626. first_entrypoint = self.entrypoint
  627. # load the second header
  628. self.load_common_header(load_file, ESPROM.ESP_IMAGE_MAGIC)
  629. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  630. if first_flash_mode != self.flash_mode:
  631. print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  632. % (first_flash_mode, self.flash_mode))
  633. if first_flash_size_freq != self.flash_size_freq:
  634. print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  635. % (first_flash_size_freq, self.flash_size_freq))
  636. if first_entrypoint != self.entrypoint:
  637. print('WARNING: Entrypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
  638. % (first_entrypoint, self.entrypoint))
  639. # load all the usual segments
  640. for _ in xrange(segments):
  641. self.load_segment(load_file)
  642. self.checksum = self.read_checksum(load_file)
  643. def default_output_name(self, input_file):
  644. """ Derive a default output name from the ELF name. """
  645. irom_segment = self.get_irom_segment()
  646. if irom_segment is not None:
  647. irom_offs = irom_segment.addr - ESPROM.IROM_MAP_START
  648. else:
  649. irom_offs = 0
  650. return "%s-0x%05x.bin" % (os.path.splitext(input_file)[0],
  651. irom_offs & ~(ESPROM.ESP_FLASH_SECTOR - 1))
  652. def save(self, filename):
  653. with open(filename, 'wb') as f:
  654. # Save first header for irom0 segment
  655. f.write(struct.pack('<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
  656. self.flash_mode, self.flash_size_freq, self.entrypoint))
  657. irom_segment = self.get_irom_segment()
  658. if irom_segment is not None:
  659. # save irom0 segment, make sure it has load addr 0 in the file
  660. irom_segment = irom_segment.copy_with_new_addr(0)
  661. self.save_segment(f, irom_segment)
  662. # second header, matches V1 header and contains loadable segments
  663. normal_segments = self.get_non_irom_segments()
  664. self.write_common_header(f, normal_segments)
  665. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  666. for segment in normal_segments:
  667. checksum = self.save_segment(f, segment, checksum)
  668. self.append_checksum(f, checksum)
  669. class ESP32FirmwareImage(BaseFirmwareImage):
  670. """ ESP32 firmware image is very similar to V1 ESP8266 image,
  671. except with an additional 16 byte reserved header at top of image,
  672. and because of new flash mapping capabilities the flash-mapped regions
  673. can be placed in the normal image (just @ 64kB padded offsets).
  674. """
  675. def __init__(self, load_file=None):
  676. super(ESP32FirmwareImage, self).__init__()
  677. self.flash_mode = 0
  678. self.flash_size_freq = 0
  679. self.version = 1
  680. self.additional_header = '\x00' * 16
  681. if load_file is not None:
  682. segments = self.load_common_header(load_file, ESPROM.ESP_IMAGE_MAGIC)
  683. self.additional_header = load_file.read(16)
  684. for i in xrange(segments):
  685. self.load_segment(load_file)
  686. self.checksum = self.read_checksum(load_file)
  687. def is_flash_addr(self, addr):
  688. return (ESP32ROM.IROM_MAP_START <= addr < ESP32ROM.IROM_MAP_END) \
  689. or (ESP32ROM.DROM_MAP_START <= addr < ESP32ROM.DROM_MAP_END)
  690. def default_output_name(self, input_file):
  691. """ Derive a default output name from the ELF name. """
  692. return "%s.bin" % (os.path.splitext(input_file)[0])
  693. def save(self, filename):
  694. padding_segments = 0
  695. with open(filename, 'wb') as f:
  696. self.write_common_header(f, self.segments)
  697. f.write(self.additional_header)
  698. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  699. last_addr = None
  700. for segment in sorted(self.segments, key=lambda s:s.addr):
  701. #print("Writing %s file @ 0x%x" % (segment, f.tell()))
  702. # IROM/DROM segment flash mappings need to align on
  703. # 64kB boundaries.
  704. #
  705. # TODO: intelligently order segments to reduce wastage
  706. # by squeezing smaller DRAM/IRAM segments into the
  707. # 64kB padding space.
  708. IROM_ALIGN = 65536
  709. # check for multiple ELF sections that live in the same flash mapping region.
  710. # this is usually a sign of a broken linker script, but if you have a legitimate
  711. # use case then let us know (we can merge segments here, but as a rule you probably
  712. # want to merge them in your linker script.)
  713. if last_addr is not None and self.is_flash_addr(last_addr) \
  714. and self.is_flash_addr(segment.addr) and segment.addr // IROM_ALIGN == last_addr // IROM_ALIGN:
  715. raise FatalError(("Segment loaded at 0x%08x lands in same 64KB flash mapping as segment loaded at 0x%08x. "+
  716. "Can't generate binary. Suggest changing linker script or ELF to merge sections.") %
  717. (segment.addr, last_addr))
  718. last_addr = segment.addr
  719. if self.is_flash_addr(segment.addr):
  720. #print("Padding from offset %08x" % f.tell())
  721. # Actual alignment required for the segment header: positioned so that
  722. # after we write the next 8 byte header, file_offs % IROM_ALIGN == segment.addr % IROM_ALIGN
  723. #
  724. # (this is because the segment's vaddr may not be IROM_ALIGNed, more likely is aligned
  725. # IROM_ALIGN+0x10 to account for longest possible header.
  726. align_past = (segment.addr % IROM_ALIGN) - self.SEG_HEADER_LEN
  727. #print "segment starts 0x%x so aligning header at +0x%x" % (segment.addr, align_past)
  728. assert (align_past + self.SEG_HEADER_LEN) == (segment.addr % IROM_ALIGN)
  729. # subtract SEG_HEADER_LEN a second time, as the padding block has a header as well
  730. pad_len = ( IROM_ALIGN - (f.tell() % IROM_ALIGN) ) + align_past - self.SEG_HEADER_LEN
  731. if pad_len < 0:
  732. pad_len += IROM_ALIGN
  733. if pad_len > 0:
  734. #print("Calculated pad length %08x to place next header @ %08x" % (pad_len, f.tell()+pad_len))
  735. null = ImageSegment(0, '\x00' * pad_len, f.tell())
  736. checksum = self.save_segment(f, null, checksum)
  737. #print("After padding, at file offset %08x" % f.tell())
  738. padding_segments += 1
  739. #print "Comparing file offs %x (data @ %x) with segment load addr %x" % (f.tell(), f.tell() + 8, segment.addr)
  740. # verify that after the 8 byte header is added, were are at the correct offset relative to the segment's vaddr
  741. assert (f.tell() + 8) % IROM_ALIGN == segment.addr % IROM_ALIGN
  742. checksum = self.save_segment(f, segment, checksum)
  743. self.append_checksum(f, checksum)
  744. # kinda hacky: go back to the initial header and write the new segment count
  745. # that includes padding segments. Luckily(?) this header is not checksummed
  746. f.seek(1)
  747. f.write(chr(len(self.segments) + padding_segments))
  748. class ELFFile(object):
  749. SEC_TYPE_PROGBITS = 0x01
  750. SEC_TYPE_STRTAB = 0x03
  751. def __init__(self, name):
  752. # Load sections from the ELF file
  753. self.name = name
  754. with open(self.name, 'rb') as f:
  755. self._read_elf_file(f)
  756. def _read_elf_file(self, f):
  757. # read the ELF file header
  758. LEN_FILE_HEADER = 0x34
  759. try:
  760. (ident,_type,machine,_version,
  761. self.entrypoint,_phoff,shoff,_flags,
  762. _ehsize, _phentsize,_phnum,_shentsize,
  763. _shnum,shstrndx) = struct.unpack("<16sHHLLLLLHHHHHH", f.read(LEN_FILE_HEADER))
  764. except struct.error as e:
  765. raise FatalError("Failed to read a valid ELF header from %s: %s" % (self.name, e))
  766. if ident[0] != '\x7f' or ident[1:4] != 'ELF':
  767. raise FatalError("%s has invalid ELF magic header" % self.name)
  768. if machine != 0x5e:
  769. raise FatalError("%s does not appear to be an Xtensa ELF file. e_machine=%04x" % (self.name, machine))
  770. self._read_sections(f, shoff, shstrndx)
  771. def _read_sections(self, f, section_header_offs, shstrndx):
  772. f.seek(section_header_offs)
  773. section_header = f.read()
  774. LEN_SEC_HEADER = 0x28
  775. if len(section_header) == 0:
  776. raise FatalError("No section header found at offset %04x in ELF file." % section_header_offs)
  777. if len(section_header) % LEN_SEC_HEADER != 0:
  778. print 'WARNING: Unexpected ELF section header length %04x is not mod-%02x' % (len(section_header),LEN_SEC_HEADER)
  779. # walk through the section header and extract all sections
  780. section_header_offsets = range(0, len(section_header), LEN_SEC_HEADER)
  781. def read_section_header(offs):
  782. name_offs,sec_type,_flags,lma,sec_offs,size = struct.unpack_from("<LLLLLL", section_header[offs:])
  783. return (name_offs, sec_type, lma, size, sec_offs)
  784. all_sections = [read_section_header(offs) for offs in section_header_offsets]
  785. prog_sections = [s for s in all_sections if s[1] == ELFFile.SEC_TYPE_PROGBITS]
  786. # search for the string table section
  787. if not shstrndx * LEN_SEC_HEADER in section_header_offsets:
  788. raise FatalError("ELF file has no STRTAB section at shstrndx %d" % shstrndx)
  789. _,sec_type,_,sec_size,sec_offs = read_section_header(shstrndx * LEN_SEC_HEADER)
  790. if sec_type != ELFFile.SEC_TYPE_STRTAB:
  791. print 'WARNING: ELF file has incorrect STRTAB section type 0x%02x' % sec_type
  792. f.seek(sec_offs)
  793. string_table = f.read(sec_size)
  794. # build the real list of ELFSections by reading the actual section names from the
  795. # string table section, and actual data for each section from the ELF file itself
  796. def lookup_string(offs):
  797. raw = string_table[offs:]
  798. return raw[:raw.index('\x00')]
  799. def read_data(offs,size):
  800. f.seek(offs)
  801. return f.read(size)
  802. prog_sections = [ELFSection(lookup_string(n_offs), lma, read_data(offs, size)) for (n_offs, _type, lma, size, offs) in prog_sections
  803. if lma != 0]
  804. self.sections = prog_sections
  805. class CesantaFlasher(object):
  806. # From stub_flasher.h
  807. CMD_FLASH_WRITE = 1
  808. CMD_FLASH_READ = 2
  809. CMD_FLASH_DIGEST = 3
  810. CMD_FLASH_ERASE_CHIP = 5
  811. CMD_BOOT_FW = 6
  812. def __init__(self, esp, baud_rate=0):
  813. print 'Running Cesanta flasher stub...'
  814. if baud_rate <= ESPROM.ESP_ROM_BAUD: # don't change baud rates if we already synced at that rate
  815. baud_rate = 0
  816. self._esp = esp
  817. esp.run_stub(json.loads(_CESANTA_FLASHER_STUB), [baud_rate])
  818. if baud_rate > 0:
  819. esp._port.baudrate = baud_rate
  820. # Read the greeting.
  821. p = esp.read()
  822. if p != 'OHAI':
  823. raise FatalError('Failed to connect to the flasher (got %s)' % hexify(p))
  824. def flash_write(self, addr, data, show_progress=False):
  825. assert addr % self._esp.ESP_FLASH_SECTOR == 0, 'Address must be sector-aligned'
  826. assert len(data) % self._esp.ESP_FLASH_SECTOR == 0, 'Length must be sector-aligned'
  827. sys.stdout.write('Writing %d @ 0x%x... ' % (len(data), addr))
  828. sys.stdout.flush()
  829. self._esp.write(struct.pack('<B', self.CMD_FLASH_WRITE))
  830. self._esp.write(struct.pack('<III', addr, len(data), 1))
  831. num_sent, num_written = 0, 0
  832. while num_written < len(data):
  833. p = self._esp.read()
  834. if len(p) == 4:
  835. num_written = struct.unpack('<I', p)[0]
  836. elif len(p) == 1:
  837. status_code = struct.unpack('<B', p)[0]
  838. raise FatalError('Write failure, status: %x' % status_code)
  839. else:
  840. raise FatalError('Unexpected packet while writing: %s' % hexify(p))
  841. if show_progress:
  842. progress = '%d (%d %%)' % (num_written, num_written * 100.0 / len(data))
  843. sys.stdout.write(progress + '\b' * len(progress))
  844. sys.stdout.flush()
  845. while num_sent - num_written < 5120:
  846. self._esp._port.write(data[num_sent:num_sent + 1024])
  847. num_sent += 1024
  848. p = self._esp.read()
  849. if len(p) != 16:
  850. raise FatalError('Expected digest, got: %s' % hexify(p))
  851. digest = hexify(p).upper()
  852. expected_digest = hashlib.md5(data).hexdigest().upper()
  853. print
  854. if digest != expected_digest:
  855. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  856. p = self._esp.read()
  857. if len(p) != 1:
  858. raise FatalError('Expected status, got: %s' % hexify(p))
  859. status_code = struct.unpack('<B', p)[0]
  860. if status_code != 0:
  861. raise FatalError('Write failure, status: %x' % status_code)
  862. def flash_read(self, addr, length, show_progress=False):
  863. sys.stdout.write('Reading %d @ 0x%x... ' % (length, addr))
  864. sys.stdout.flush()
  865. self._esp.write(struct.pack('<B', self.CMD_FLASH_READ))
  866. # USB may not be able to keep up with the read rate, especially at
  867. # higher speeds. Since we don't have flow control, this will result in
  868. # data loss. Hence, we use small packet size and only allow small
  869. # number of bytes in flight, which we can reasonably expect to fit in
  870. # the on-chip FIFO. max_in_flight = 64 works for CH340G, other chips may
  871. # have longer FIFOs and could benefit from increasing max_in_flight.
  872. self._esp.write(struct.pack('<IIII', addr, length, 32, 64))
  873. data = ''
  874. while True:
  875. p = self._esp.read()
  876. data += p
  877. self._esp.write(struct.pack('<I', len(data)))
  878. if show_progress and (len(data) % 1024 == 0 or len(data) == length):
  879. progress = '%d (%d %%)' % (len(data), len(data) * 100.0 / length)
  880. sys.stdout.write(progress + '\b' * len(progress))
  881. sys.stdout.flush()
  882. if len(data) == length:
  883. break
  884. if len(data) > length:
  885. raise FatalError('Read more than expected')
  886. p = self._esp.read()
  887. if len(p) != 16:
  888. raise FatalError('Expected digest, got: %s' % hexify(p))
  889. expected_digest = hexify(p).upper()
  890. digest = hashlib.md5(data).hexdigest().upper()
  891. print
  892. if digest != expected_digest:
  893. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  894. p = self._esp.read()
  895. if len(p) != 1:
  896. raise FatalError('Expected status, got: %s' % hexify(p))
  897. status_code = struct.unpack('<B', p)[0]
  898. if status_code != 0:
  899. raise FatalError('Write failure, status: %x' % status_code)
  900. return data
  901. def flash_digest(self, addr, length, digest_block_size=0):
  902. self._esp.write(struct.pack('<B', self.CMD_FLASH_DIGEST))
  903. self._esp.write(struct.pack('<III', addr, length, digest_block_size))
  904. digests = []
  905. while True:
  906. p = self._esp.read()
  907. if len(p) == 16:
  908. digests.append(p)
  909. elif len(p) == 1:
  910. status_code = struct.unpack('<B', p)[0]
  911. if status_code != 0:
  912. raise FatalError('Write failure, status: %x' % status_code)
  913. break
  914. else:
  915. raise FatalError('Unexpected packet: %s' % hexify(p))
  916. return digests[-1], digests[:-1]
  917. def boot_fw(self):
  918. self._esp.write(struct.pack('<B', self.CMD_BOOT_FW))
  919. p = self._esp.read()
  920. if len(p) != 1:
  921. raise FatalError('Expected status, got: %s' % hexify(p))
  922. status_code = struct.unpack('<B', p)[0]
  923. if status_code != 0:
  924. raise FatalError('Boot failure, status: %x' % status_code)
  925. def flash_erase(self):
  926. self._esp.write(struct.pack('<B', self.CMD_FLASH_ERASE_CHIP))
  927. p = self._esp.read()
  928. if len(p) != 1:
  929. raise FatalError('Expected status, got: %s' % hexify(p))
  930. status_code = struct.unpack('<B', p)[0]
  931. if status_code != 0:
  932. raise FatalError('Chip erase failure, status: %x' % status_code)
  933. def slip_reader(port):
  934. """Generator to read SLIP packets from a serial port.
  935. Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
  936. Designed to avoid too many calls to serial.read(1), which can bog
  937. down on slow systems.
  938. """
  939. partial_packet = None
  940. in_escape = False
  941. while True:
  942. waiting = port.inWaiting()
  943. read_bytes = port.read(1 if waiting == 0 else waiting)
  944. if read_bytes == '':
  945. raise FatalError("Timed out waiting for packet %s" % ("header" if partial_packet is None else "content"))
  946. for b in read_bytes:
  947. if partial_packet is None: # waiting for packet header
  948. if b == '\xc0':
  949. partial_packet = ""
  950. else:
  951. raise FatalError('Invalid head of packet (%r)' % b)
  952. elif in_escape: # part-way through escape sequence
  953. in_escape = False
  954. if b == '\xdc':
  955. partial_packet += '\xc0'
  956. elif b == '\xdd':
  957. partial_packet += '\xdb'
  958. else:
  959. raise FatalError('Invalid SLIP escape (%r%r)' % ('\xdb', b))
  960. elif b == '\xdb': # start of escape sequence
  961. in_escape = True
  962. elif b == '\xc0': # end of packet
  963. yield partial_packet
  964. partial_packet = None
  965. else: # normal byte in packet
  966. partial_packet += b
  967. def arg_auto_int(x):
  968. return int(x, 0)
  969. def div_roundup(a, b):
  970. """ Return a/b rounded up to nearest integer,
  971. equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
  972. without possible floating point accuracy errors.
  973. """
  974. return (int(a) + int(b) - 1) / int(b)
  975. def binutils_safe_path(p):
  976. """Returns a 'safe' version of path 'p' to pass to binutils
  977. Only does anything under Cygwin Python, where cygwin paths need to
  978. be translated to Windows paths if the binutils wasn't compiled
  979. using Cygwin (should also work with binutils compiled using
  980. Cygwin, see #73.)
  981. """
  982. if sys.platform == "cygwin":
  983. try:
  984. return subprocess.check_output(["cygpath", "-w", p]).rstrip('\n')
  985. except subprocess.CalledProcessError:
  986. print "WARNING: Failed to call cygpath to sanitise Cygwin path."
  987. return p
  988. def align_file_position(f, size):
  989. """ Align the position in the file to the next block of specified size """
  990. align = (size - 1) - (f.tell() % size)
  991. f.seek(align, 1)
  992. def hexify(s):
  993. return ''.join('%02X' % ord(c) for c in s)
  994. def unhexify(hs):
  995. s = ''
  996. for i in range(0, len(hs) - 1, 2):
  997. s += chr(int(hs[i] + hs[i + 1], 16))
  998. return s
  999. class FatalError(RuntimeError):
  1000. """
  1001. Wrapper class for runtime errors that aren't caused by internal bugs, but by
  1002. ESP8266 responses or input content.
  1003. """
  1004. def __init__(self, message):
  1005. RuntimeError.__init__(self, message)
  1006. @staticmethod
  1007. def WithResult(message, result):
  1008. """
  1009. Return a fatal error object that appends the hex values of
  1010. 'result' as a string formatted argument.
  1011. """
  1012. message += " (result was %s)" % ", ".join(hex(ord(x)) for x in result)
  1013. return FatalError(message)
  1014. # "Operation" commands, executable at command line. One function each
  1015. #
  1016. # Each function takes either two args (<ESPROM instance>, <args>) or a single <args>
  1017. # argument.
  1018. def load_ram(esp, args):
  1019. image = LoadFirmwareImage(esp, args.filename)
  1020. print 'RAM boot...'
  1021. for (offset, size, data) in image.segments:
  1022. print 'Downloading %d bytes at %08x...' % (size, offset),
  1023. sys.stdout.flush()
  1024. esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset)
  1025. seq = 0
  1026. while len(data) > 0:
  1027. esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
  1028. data = data[esp.ESP_RAM_BLOCK:]
  1029. seq += 1
  1030. print 'done!'
  1031. print 'All segments done, executing at %08x' % image.entrypoint
  1032. esp.mem_finish(image.entrypoint)
  1033. def read_mem(esp, args):
  1034. print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address))
  1035. def write_mem(esp, args):
  1036. esp.write_reg(args.address, args.value, args.mask, 0)
  1037. print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address)
  1038. def dump_mem(esp, args):
  1039. f = file(args.filename, 'wb')
  1040. for i in xrange(args.size / 4):
  1041. d = esp.read_reg(args.address + (i * 4))
  1042. f.write(struct.pack('<I', d))
  1043. if f.tell() % 1024 == 0:
  1044. print '\r%d bytes read... (%d %%)' % (f.tell(),
  1045. f.tell() * 100 / args.size),
  1046. sys.stdout.flush()
  1047. print 'Done!'
  1048. def write_flash(esp, args):
  1049. # This splitting of functionality will go away eventually,
  1050. # but for now this is the easiest way :|
  1051. if isinstance(esp, ESP32ROM):
  1052. write_flash_no_stub(esp, args)
  1053. else:
  1054. write_flash_via_stub(esp, args)
  1055. def write_flash_via_stub(esp, args):
  1056. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1057. flash_size_freq = esp.parse_flash_size_arg(args.flash_size)
  1058. flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1059. flash_params = struct.pack('BB', flash_mode, flash_size_freq)
  1060. flasher = CesantaFlasher(esp, args.baud)
  1061. for address, argfile in args.addr_filename:
  1062. image = argfile.read()
  1063. argfile.seek(0) # rewind in case we need it again
  1064. # Fix sflash config data.
  1065. if address == 0 and image[0] == '\xe9':
  1066. print 'Flash params set to 0x%02x%02x' % (flash_mode, flash_size_freq)
  1067. image = image[0:2] + flash_params + image[4:]
  1068. # Pad to sector size, which is the minimum unit of writing (erasing really).
  1069. if len(image) % esp.ESP_FLASH_SECTOR != 0:
  1070. image += '\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR))
  1071. t = time.time()
  1072. flasher.flash_write(address, image, not args.no_progress)
  1073. t = time.time() - t
  1074. print ('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  1075. % (len(image), address, t, len(image) / t * 8 / 1000))
  1076. print 'Leaving...'
  1077. if args.verify:
  1078. print 'Verifying just-written flash...'
  1079. _verify_flash(flasher, args, flash_params)
  1080. flasher.boot_fw()
  1081. def write_flash_no_stub(esp, args):
  1082. """Write flash directly via the bootloader, no stub
  1083. The existence of this function is a hack. Before this is done,
  1084. the stub needs to speak the ESP bootloader protocol so
  1085. we can roll all this code up into the write_flash().
  1086. This function also includes some support for Espressif internal
  1087. testing functions that probably aren't useful for most people, and
  1088. need to go live somewhere... maybe a generic "bootloader command"
  1089. function or something?
  1090. """
  1091. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1092. flash_size_freq = esp.parse_flash_size_arg(args.flash_size)
  1093. flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1094. flash_info = struct.pack('BB', flash_mode, flash_size_freq)
  1095. print "\n\n"
  1096. print "********************************"
  1097. uc_is_hspi = int(args.ucIsHspi,16)
  1098. uc_is_legacy = int(args.ucIsLegacy,16) & 0xff
  1099. print "IS HSPI: 0x%08x" % (uc_is_hspi),type(uc_is_hspi)
  1100. print "--------------------------"
  1101. print "IS LEGACY: 0x%02x" % uc_is_legacy,type(uc_is_legacy)
  1102. print "*********************************"
  1103. print "SENDING SPI ATTACH COMMAND"
  1104. print "--------------"
  1105. esp.flash_spi_attach_req(uc_is_hspi,uc_is_legacy)
  1106. print "START DOWNLOADING..."
  1107. for address, argfile in args.addr_filename:
  1108. print 'Erasing flash...'
  1109. if args.compress:
  1110. uncimage = argfile.read()
  1111. calcmd5 = hashlib.md5(uncimage).hexdigest()
  1112. uncsize = len(uncimage)
  1113. image = zlib.compress(uncimage, 9)
  1114. blocks = div_roundup(len(image), esp.ESP_FLASH_BLOCK)
  1115. esp.flash_defl_begin(len(uncimage),len(image), address)
  1116. else:
  1117. image = argfile.read()
  1118. calcmd5 = hashlib.md5(image).hexdigest()
  1119. uncsize = len(image)
  1120. blocks = div_roundup(len(image), esp.ESP_FLASH_BLOCK)
  1121. esp.flash_begin(blocks * esp.ESP_FLASH_BLOCK, address)
  1122. argfile.seek(0) # in case we need it again
  1123. seq = 0
  1124. written = 0
  1125. t = time.time()
  1126. header_block = None
  1127. while len(image) > 0:
  1128. print '\rWriting at 0x%08x... (%d %%)' % (address + seq * esp.ESP_FLASH_BLOCK, 100 * (seq + 1) / blocks),
  1129. sys.stdout.flush()
  1130. block = image[0:esp.ESP_FLASH_BLOCK]
  1131. if args.compress:
  1132. esp.flash_defl_block(block, seq)
  1133. else:
  1134. # Pad the last block
  1135. block = block + '\xff' * (esp.ESP_FLASH_BLOCK - len(block))
  1136. # Fix sflash config data
  1137. if address == 0 and seq == 0 and block[0] == '\xe9':
  1138. block = block[0:2] + flash_info + block[4:]
  1139. header_block = block
  1140. esp.flash_block(block, seq)
  1141. image = image[esp.ESP_FLASH_BLOCK:]
  1142. seq += 1
  1143. written += len(block)
  1144. t = time.time() - t
  1145. print '\rWrote %d bytes at 0x%08x in %.1f seconds (%.1f kbit/s)...' % (written, address, t, written / t * 8 / 1000)
  1146. res = esp.flash_md5sum(address, uncsize)
  1147. if res != calcmd5:
  1148. print 'File md5: %s' % calcmd5
  1149. print 'Flash md5: %s' % res
  1150. raise FatalError("MD5 of file does not match data in flash!")
  1151. else:
  1152. print 'Hash of data verified.'
  1153. print '\nLeaving...'
  1154. if args.flash_mode == 'dio':
  1155. esp.flash_unlock_dio()
  1156. else:
  1157. esp.flash_begin(0, 0)
  1158. if args.compress:
  1159. esp.flash_defl_finish(False)
  1160. else:
  1161. esp.flash_finish(False)
  1162. if args.verify:
  1163. print 'Verifying just-written flash...'
  1164. verify_flash(esp, args, header_block)
  1165. def image_info(args):
  1166. image = LoadFirmwareImage(args.chip, args.filename)
  1167. print('Image version: %d' % image.version)
  1168. print('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set'
  1169. print '%d segments' % len(image.segments)
  1170. print
  1171. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  1172. idx = 0
  1173. for seg in image.segments:
  1174. idx += 1
  1175. print 'Segment %d: %r' % (idx, seg)
  1176. checksum = ESPROM.checksum(seg.data, checksum)
  1177. print
  1178. print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!')
  1179. def make_image(args):
  1180. image = ESPFirmwareImage()
  1181. if len(args.segfile) == 0:
  1182. raise FatalError('No segments specified')
  1183. if len(args.segfile) != len(args.segaddr):
  1184. raise FatalError('Number of specified files does not match number of specified addresses')
  1185. for (seg, addr) in zip(args.segfile, args.segaddr):
  1186. data = file(seg, 'rb').read()
  1187. image.segments.append(ImageSegment(addr, data))
  1188. image.entrypoint = args.entrypoint
  1189. image.save(args.output)
  1190. def elf2image(args):
  1191. e = ELFFile(args.input)
  1192. if args.chip == 'auto': # Default to ESP8266 for backwards compatibility
  1193. print "Creating image for ESP8266..."
  1194. args.chip == 'esp8266'
  1195. if args.chip == 'esp31':
  1196. raise FatalError("No elf2image support for ESP31. Use gen_appimage.py from the ESP31 SDK")
  1197. elif args.chip == 'esp32':
  1198. image = ESP32FirmwareImage()
  1199. elif args.version == '1': # ESP8266
  1200. image = ESPFirmwareImage()
  1201. else:
  1202. image = OTAFirmwareImage()
  1203. image.entrypoint = e.entrypoint
  1204. image.segments = e.sections # ELFSection is a subclass of ImageSegment
  1205. image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  1206. image.flash_size_freq = ESP8266ROM.FLASH_SIZES[args.flash_size]
  1207. image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  1208. if args.output is None:
  1209. args.output = image.default_output_name(args.input)
  1210. image.save(args.output)
  1211. def read_mac(esp, args):
  1212. mac = esp.read_mac()
  1213. print 'MAC: %s' % ':'.join(map(lambda x: '%02x' % x, mac))
  1214. def chip_id(esp, args):
  1215. chipid = esp.chip_id()
  1216. print 'Chip ID: 0x%08x' % chipid
  1217. def erase_flash(esp, args):
  1218. print 'Erasing flash (this may take a while)...'
  1219. flasher = CesantaFlasher(esp, args.baud)
  1220. flasher.flash_erase()
  1221. print 'Erase completed successfully.'
  1222. def run(esp, args):
  1223. esp.run()
  1224. def flash_id(esp, args):
  1225. flash_id = esp.flash_id()
  1226. print 'Manufacturer: %02x' % (flash_id & 0xff)
  1227. print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff)
  1228. def read_flash(esp, args):
  1229. flasher = CesantaFlasher(esp, args.baud)
  1230. t = time.time()
  1231. data = flasher.flash_read(args.address, args.size, not args.no_progress)
  1232. t = time.time() - t
  1233. print ('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  1234. % (len(data), args.address, t, len(data) / t * 8 / 1000))
  1235. file(args.filename, 'wb').write(data)
  1236. def _verify_flash(flasher, args, flash_params=None):
  1237. differences = False
  1238. for address, argfile in args.addr_filename:
  1239. image = argfile.read()
  1240. argfile.seek(0) # rewind in case we need it again
  1241. if address == 0 and image[0] == '\xe9' and flash_params is not None:
  1242. image = image[0:2] + flash_params + image[4:]
  1243. image_size = len(image)
  1244. print 'Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name)
  1245. # Try digest first, only read if there are differences.
  1246. digest, _ = flasher.flash_digest(address, image_size)
  1247. digest = hexify(digest).upper()
  1248. expected_digest = hashlib.md5(image).hexdigest().upper()
  1249. if digest == expected_digest:
  1250. print '-- verify OK (digest matched)'
  1251. continue
  1252. else:
  1253. differences = True
  1254. if getattr(args, 'diff', 'no') != 'yes':
  1255. print '-- verify FAILED (digest mismatch)'
  1256. continue
  1257. flash = flasher.flash_read(address, image_size)
  1258. assert flash != image
  1259. diff = [i for i in xrange(image_size) if flash[i] != image[i]]
  1260. print '-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0])
  1261. for d in diff:
  1262. print ' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d]))
  1263. if differences:
  1264. raise FatalError("Verify failed.")
  1265. def verify_flash(esp, args, flash_params=None):
  1266. flasher = CesantaFlasher(esp)
  1267. _verify_flash(flasher, args, flash_params)
  1268. def version(args):
  1269. print __version__
  1270. #
  1271. # End of operations functions
  1272. #
  1273. def main():
  1274. parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
  1275. parser.add_argument('--chip', '-c',
  1276. help='Target chip type',
  1277. choices=['auto', 'esp8266', 'esp31', 'esp32'],
  1278. default=os.environ.get('ESPTOOL_CHIP', 'auto'))
  1279. parser.add_argument(
  1280. '--port', '-p',
  1281. help='Serial port device',
  1282. default=os.environ.get('ESPTOOL_PORT', ESPROM.DEFAULT_PORT))
  1283. parser.add_argument(
  1284. '--baud', '-b',
  1285. help='Serial port baud rate used when flashing/reading',
  1286. type=arg_auto_int,
  1287. default=os.environ.get('ESPTOOL_BAUD', ESPROM.ESP_ROM_BAUD))
  1288. subparsers = parser.add_subparsers(
  1289. dest='operation',
  1290. help='Run esptool {command} -h for additional help')
  1291. parser_load_ram = subparsers.add_parser(
  1292. 'load_ram',
  1293. help='Download an image to RAM and execute')
  1294. parser_load_ram.add_argument('filename', help='Firmware image')
  1295. parser_dump_mem = subparsers.add_parser(
  1296. 'dump_mem',
  1297. help='Dump arbitrary memory to disk')
  1298. parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
  1299. parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  1300. parser_dump_mem.add_argument('filename', help='Name of binary dump')
  1301. parser_read_mem = subparsers.add_parser(
  1302. 'read_mem',
  1303. help='Read arbitrary memory location')
  1304. parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
  1305. parser_write_mem = subparsers.add_parser(
  1306. 'write_mem',
  1307. help='Read-modify-write to arbitrary memory location')
  1308. parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
  1309. parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
  1310. parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int)
  1311. def add_spi_flash_subparsers(parent):
  1312. """ Add common parser arguments for SPI flash properties """
  1313. parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
  1314. choices=['40m', '26m', '20m', '80m'],
  1315. default=os.environ.get('ESPTOOL_FF', '40m'))
  1316. parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
  1317. choices=['qio', 'qout', 'dio', 'dout'],
  1318. default=os.environ.get('ESPTOOL_FM', 'qio'))
  1319. parent.add_argument('--flash_size', '-fs', help='SPI Flash size in MegaBytes (1MB, 2MB, 4MB, 8MB, 16M)'
  1320. ' plus ESP8266-only (256KB, 512KB, 2MB-c1, 4MB-c1, 4MB-2)',
  1321. action=FlashSizeAction,
  1322. default=os.environ.get('ESPTOOL_FS', '1MB'))
  1323. parser_write_flash = subparsers.add_parser(
  1324. 'write_flash',
  1325. help='Write a binary blob to flash')
  1326. parser_write_flash.add_argument('addr_filename', metavar='<address> <filename>', help='Address followed by binary filename, separated by space',
  1327. action=AddrFilenamePairAction)
  1328. add_spi_flash_subparsers(parser_write_flash)
  1329. parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  1330. parser_write_flash.add_argument('--verify', help='Verify just-written data (only necessary if very cautious, data is already CRCed', action='store_true')
  1331. parser_write_flash.add_argument('--ucIsHspi', '-ih', help='Config SPI PORT/PINS (Espressif internal feature)',default='0')
  1332. parser_write_flash.add_argument('--ucIsLegacy', '-il', help='Config SPI LEGACY (Espressif internal feature)',default='0')
  1333. parser_write_flash.add_argument('--compress', '-z', help='Compress data in transfer',action="store_true")
  1334. subparsers.add_parser(
  1335. 'run',
  1336. help='Run application code in flash')
  1337. parser_image_info = subparsers.add_parser(
  1338. 'image_info',
  1339. help='Dump headers from an application image')
  1340. parser_image_info.add_argument('filename', help='Image file to parse')
  1341. parser_make_image = subparsers.add_parser(
  1342. 'make_image',
  1343. help='Create an application image from binary files')
  1344. parser_make_image.add_argument('output', help='Output image file')
  1345. parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
  1346. parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
  1347. parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
  1348. parser_elf2image = subparsers.add_parser(
  1349. 'elf2image',
  1350. help='Create an application image from ELF file')
  1351. parser_elf2image.add_argument('input', help='Input ELF file')
  1352. parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
  1353. parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1')
  1354. add_spi_flash_subparsers(parser_elf2image)
  1355. subparsers.add_parser(
  1356. 'read_mac',
  1357. help='Read MAC address from OTP ROM')
  1358. subparsers.add_parser(
  1359. 'chip_id',
  1360. help='Read Chip ID from OTP ROM')
  1361. subparsers.add_parser(
  1362. 'flash_id',
  1363. help='Read SPI flash manufacturer and device ID')
  1364. parser_read_flash = subparsers.add_parser(
  1365. 'read_flash',
  1366. help='Read SPI flash content')
  1367. parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
  1368. parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  1369. parser_read_flash.add_argument('filename', help='Name of binary dump')
  1370. parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  1371. parser_verify_flash = subparsers.add_parser(
  1372. 'verify_flash',
  1373. help='Verify a binary blob against flash')
  1374. parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
  1375. action=AddrFilenamePairAction)
  1376. parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
  1377. choices=['no', 'yes'], default='no')
  1378. subparsers.add_parser(
  1379. 'erase_flash',
  1380. help='Perform Chip Erase on SPI flash')
  1381. subparsers.add_parser(
  1382. 'version', help='Print esptool version')
  1383. # internal sanity check - every operation matches a module function of the same name
  1384. for operation in subparsers.choices.keys():
  1385. assert operation in globals(), "%s should be a module function" % operation
  1386. args = parser.parse_args()
  1387. print 'esptool.py v%s' % __version__
  1388. # operation function can take 1 arg (args), 2 args (esp, arg)
  1389. # or be a member function of the ESPROM class.
  1390. operation_func = globals()[args.operation]
  1391. operation_args,_,_,_ = inspect.getargspec(operation_func)
  1392. if operation_args[0] == 'esp': # operation function takes an ESPROM connection object
  1393. initial_baud = min(ESPROM.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
  1394. chip_constructor_fun = {
  1395. 'auto': ESPROM.detect_chip,
  1396. 'esp8266': ESP8266ROM,
  1397. 'esp31': ESP31ROM,
  1398. 'esp32': ESP32ROM,
  1399. }[args.chip]
  1400. esp = chip_constructor_fun(args.port, initial_baud)
  1401. # try to set a higher baud, this is a no-op if we need to
  1402. # wait for the flasher stub to kick in before doing this.
  1403. esp.change_baud(args.baud)
  1404. operation_func(esp, args)
  1405. else:
  1406. operation_func(args)
  1407. class FlashSizeAction(argparse.Action):
  1408. """ Custom flash size parser class to support backwards compatibility with megabit size arguments.
  1409. (At next major relase, remove deprecated sizes and this can become a 'normal' choices= argument again.)
  1410. """
  1411. def __init__(self, option_strings, dest, nargs=1, **kwargs):
  1412. super(FlashSizeAction, self).__init__(option_strings, dest, nargs, **kwargs)
  1413. def __call__(self, parser, namespace, values, option_string=None):
  1414. try:
  1415. value = {
  1416. '2m': '256KB',
  1417. '4m': '512KB',
  1418. '8m': '1MB',
  1419. '16m': '2MB',
  1420. '32m': '4MB',
  1421. '16m-c1': '2MB-c1',
  1422. '32m-c1': '4MB-c1',
  1423. '32m-c2': '4MB-c2'
  1424. }[values[0]]
  1425. print("WARNING: Flash size arguments in megabits like '%s' are deprecated." % (values[0]))
  1426. print("Please use the equivalent size '%s'." % (value))
  1427. print("Megabit arguments may be removed in a future release.")
  1428. except KeyError:
  1429. values = values[0]
  1430. known_sizes = dict(ESP8266ROM.FLASH_SIZES)
  1431. known_sizes.update(ESP32ROM.FLASH_SIZES)
  1432. if value not in known_sizes:
  1433. raise argparse.ArgumentError(self, '%s is not a known flash size. Known sizes: %s' % (value, ", ".join(known_sizes.keys())))
  1434. setattr(namespace, self.dest, value)
  1435. class AddrFilenamePairAction(argparse.Action):
  1436. """ Custom parser class for the address/filename pairs passed as arguments """
  1437. def __init__(self, option_strings, dest, nargs='+', **kwargs):
  1438. super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
  1439. def __call__(self, parser, namespace, values, option_string=None):
  1440. # validate pair arguments
  1441. pairs = []
  1442. for i in range(0,len(values),2):
  1443. try:
  1444. address = int(values[i],0)
  1445. except ValueError as e:
  1446. raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
  1447. try:
  1448. argfile = open(values[i + 1], 'rb')
  1449. except IOError as e:
  1450. raise argparse.ArgumentError(self, e)
  1451. except IndexError:
  1452. raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
  1453. pairs.append((address, argfile))
  1454. setattr(namespace, self.dest, pairs)
  1455. # This is "wrapped" stub_flasher.c, to be loaded using run_stub.
  1456. _CESANTA_FLASHER_STUB = """\
  1457. {"code_start": 1074790404, "code": "080000601C000060000000601000006031FCFF71FCFF\
  1458. 81FCFFC02000680332D218C020004807404074DCC48608005823C0200098081BA5A9239245005803\
  1459. 1B555903582337350129230B446604DFC6F3FF21EEFFC0200069020DF0000000010078480040004A\
  1460. 0040B449004012C1F0C921D911E901DD0209312020B4ED033C2C56C2073020B43C3C56420701F5FF\
  1461. C000003C4C569206CD0EEADD860300202C4101F1FFC0000056A204C2DCF0C02DC0CC6CCAE2D1EAFF\
  1462. 0606002030F456D3FD86FBFF00002020F501E8FFC00000EC82D0CCC0C02EC0C73DEB2ADC46030020\
  1463. 2C4101E1FFC00000DC42C2DCF0C02DC056BCFEC602003C5C8601003C6C4600003C7C08312D0CD811\
  1464. C821E80112C1100DF0000C180000140010400C0000607418000064180000801800008C1800008418\
  1465. 0000881800009018000018980040880F0040A80F0040349800404C4A0040740F0040800F0040980F\
  1466. 00400099004012C1E091F5FFC961CD0221EFFFE941F9310971D9519011C01A223902E2D1180C0222\
  1467. 6E1D21E4FF31E9FF2AF11A332D0F42630001EAFFC00000C030B43C2256A31621E1FF1A2228022030\
  1468. B43C3256B31501ADFFC00000DD023C4256ED1431D6FF4D010C52D90E192E126E0101DDFFC0000021\
  1469. D2FF32A101C020004802303420C0200039022C0201D7FFC00000463300000031CDFF1A333803D023\
  1470. C03199FF27B31ADC7F31CBFF1A3328030198FFC0000056C20E2193FF2ADD060E000031C6FF1A3328\
  1471. 030191FFC0000056820DD2DD10460800000021BEFF1A2228029CE231BCFFC020F51A33290331BBFF\
  1472. C02C411A332903C0F0F4222E1D22D204273D9332A3FFC02000280E27B3F721ABFF381E1A2242A400\
  1473. 01B5FFC00000381E2D0C42A40001B3FFC0000056120801B2FFC00000C02000280EC2DC0422D2FCC0\
  1474. 2000290E01ADFFC00000222E1D22D204226E1D281E22D204E7B204291E860000126E012198FF32A0\
  1475. 042A21C54C003198FF222E1D1A33380337B202C6D6FF2C02019FFFC000002191FF318CFF1A223A31\
  1476. 019CFFC00000218DFF1C031A22C549000C02060300003C528601003C624600003C72918BFF9A1108\
  1477. 71C861D851E841F83112C1200DF00010000068100000581000007010000074100000781000007C10\
  1478. 0000801000001C4B0040803C004091FDFF12C1E061F7FFC961E941F9310971D9519011C01A662906\
  1479. 21F3FFC2D1101A22390231F2FF0C0F1A33590331EAFFF26C1AED045C2247B3028636002D0C016DFF\
  1480. C0000021E5FF41EAFF2A611A4469040622000021E4FF1A222802F0D2C0D7BE01DD0E31E0FF4D0D1A\
  1481. 3328033D0101E2FFC00000561209D03D2010212001DFFFC000004D0D2D0C3D01015DFFC0000041D5\
  1482. FFDAFF1A444804D0648041D2FF1A4462640061D1FF106680622600673F1331D0FF10338028030C43\
  1483. 853A002642164613000041CAFF222C1A1A444804202FC047328006F6FF222C1A273F3861C2FF222C\
  1484. 1A1A6668066732B921BDFF3D0C1022800148FFC0000021BAFF1C031A2201BFFFC000000C02460300\
  1485. 5C3206020000005C424600005C5291B7FF9A110871C861D851E841F83112C1200DF0B0100000C010\
  1486. 0000D010000012C1E091FEFFC961D951E9410971F931CD039011C0ED02DD0431A1FF9C1422A06247\
  1487. B302062D0021F4FF1A22490286010021F1FF1A223902219CFF2AF12D0F011FFFC00000461C0022D1\
  1488. 10011CFFC0000021E9FFFD0C1A222802C7B20621E6FF1A22F8022D0E3D014D0F0195FFC000008C52\
  1489. 22A063C6180000218BFF3D01102280F04F200111FFC00000AC7D22D1103D014D0F010DFFC0000021\
  1490. D6FF32D110102280010EFFC0000021D3FF1C031A220185FFC00000FAEEF0CCC056ACF821CDFF317A\
  1491. FF1A223A310105FFC0000021C9FF1C031A22017CFFC000002D0C91C8FF9A110871C861D851E841F8\
  1492. 3112C1200DF0000200600000001040020060FFFFFF0012C1E00C02290131FAFF21FAFF026107C961\
  1493. C02000226300C02000C80320CC10564CFF21F5FFC02000380221F4FF20231029010C432D010163FF\
  1494. C0000008712D0CC86112C1200DF00080FE3F8449004012C1D0C9A109B17CFC22C1110C13C51C0026\
  1495. 1202463000220111C24110B68202462B0031F5FF3022A02802A002002D011C03851A0066820A2801\
  1496. 32210105A6FF0607003C12C60500000010212032A01085180066A20F2221003811482105B3FF2241\
  1497. 10861A004C1206FDFF2D011C03C5160066B20E280138114821583185CFFF06F7FF005C1286F5FF00\
  1498. 10212032A01085140066A20D2221003811482105E1FF06EFFF0022A06146EDFF45F0FFC6EBFF0000\
  1499. 01D2FFC0000006E9FF000C022241100C1322C110C50F00220111060600000022C1100C13C50E0022\
  1500. 011132C2FA303074B6230206C8FF08B1C8A112C1300DF0000000000010404F484149007519031027\
  1501. 000000110040A8100040BC0F0040583F0040CC2E00401CE20040D83900408000004021F4FF12C1E0\
  1502. C961C80221F2FF097129010C02D951C91101F4FFC0000001F3FFC00000AC2C22A3E801F2FFC00000\
  1503. 21EAFFC031412A233D0C01EFFFC000003D0222A00001EDFFC00000C1E4FF2D0C01E8FFC000002D01\
  1504. 32A004450400C5E7FFDD022D0C01E3FFC00000666D1F4B2131DCFF4600004B22C0200048023794F5\
  1505. 31D9FFC0200039023DF08601000001DCFFC000000871C861D85112C1200DF000000012C1F0026103\
  1506. 01EAFEC00000083112C1100DF000643B004012C1D0E98109B1C9A1D991F97129013911E2A0C001FA\
  1507. FFC00000CD02E792F40C0DE2A0C0F2A0DB860D00000001F4FFC00000204220E71240F7921C226102\
  1508. 01EFFFC0000052A0DC482157120952A0DD571205460500004D0C3801DA234242001BDD3811379DC5\
  1509. C6000000000C0DC2A0C001E3FFC00000C792F608B12D0DC8A1D891E881F87112C1300DF00000", "\
  1510. entry": 1074792180, "num_params": 1, "params_start": 1074790400, "data": "FE0510\
  1511. 401A0610403B0610405A0610407A061040820610408C0610408C061040", "data_start": 10736\
  1512. 43520}
  1513. """
  1514. if __name__ == '__main__':
  1515. try:
  1516. main()
  1517. except FatalError as e:
  1518. print '\nA fatal error occurred: %s' % e
  1519. sys.exit(2)