esptool.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. #
  9. # This program is free software; you can redistribute it and/or modify it under
  10. # the terms of the GNU General Public License as published by the Free Software
  11. # Foundation; either version 2 of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful, but WITHOUT
  14. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along with
  18. # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  19. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. import argparse
  21. import hashlib
  22. import inspect
  23. import json
  24. import os
  25. import serial
  26. import struct
  27. import subprocess
  28. import sys
  29. import tempfile
  30. import time
  31. __version__ = "1.2-dev"
  32. class ESPROM(object):
  33. # These are the currently known commands supported by the ROM
  34. ESP_FLASH_BEGIN = 0x02
  35. ESP_FLASH_DATA = 0x03
  36. ESP_FLASH_END = 0x04
  37. ESP_MEM_BEGIN = 0x05
  38. ESP_MEM_END = 0x06
  39. ESP_MEM_DATA = 0x07
  40. ESP_SYNC = 0x08
  41. ESP_WRITE_REG = 0x09
  42. ESP_READ_REG = 0x0a
  43. # Maximum block sized for RAM and Flash writes, respectively.
  44. ESP_RAM_BLOCK = 0x1800
  45. ESP_FLASH_BLOCK = 0x400
  46. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  47. ESP_ROM_BAUD = 115200
  48. # First byte of the application image
  49. ESP_IMAGE_MAGIC = 0xe9
  50. # Initial state for the checksum routine
  51. ESP_CHECKSUM_MAGIC = 0xef
  52. # OTP ROM addresses
  53. ESP_OTP_MAC0 = 0x3ff00050
  54. ESP_OTP_MAC1 = 0x3ff00054
  55. ESP_OTP_MAC3 = 0x3ff0005c
  56. # Flash sector size, minimum unit of erase.
  57. ESP_FLASH_SECTOR = 0x1000
  58. def __init__(self, port=0, baud=ESP_ROM_BAUD):
  59. self._port = serial.Serial(port)
  60. self._slip_reader = slip_reader(port)
  61. # setting baud rate in a separate step is a workaround for
  62. # CH341 driver on some Linux versions (this opens at 9600 then
  63. # sets), shouldn't matter for other platforms/drivers. See
  64. # https://github.com/themadinventor/esptool/issues/44#issuecomment-107094446
  65. self._port.baudrate = baud
  66. """ Read a SLIP packet from the serial port """
  67. def read(self):
  68. return self._slip_reader.next()
  69. """ Write bytes to the serial port while performing SLIP escaping """
  70. def write(self, packet):
  71. buf = '\xc0' \
  72. + (packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc')) \
  73. + '\xc0'
  74. self._port.write(buf)
  75. """ Calculate checksum of a blob, as it is defined by the ROM """
  76. @staticmethod
  77. def checksum(data, state=ESP_CHECKSUM_MAGIC):
  78. for b in data:
  79. state ^= ord(b)
  80. return state
  81. """ Send a request and read the response """
  82. def command(self, op=None, data=None, chk=0):
  83. if op is not None:
  84. pkt = struct.pack('<BBHI', 0x00, op, len(data), chk) + data
  85. self.write(pkt)
  86. # tries to get a response until that response has the
  87. # same operation as the request or a retries limit has
  88. # exceeded. This is needed for some esp8266s that
  89. # reply with more sync responses than expected.
  90. for retry in xrange(100):
  91. p = self.read()
  92. if len(p) < 8:
  93. continue
  94. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', p[:8])
  95. if resp != 1:
  96. continue
  97. body = p[8:]
  98. if op is None or op_ret == op:
  99. return val, body # valid response received
  100. raise FatalError("Response doesn't match request")
  101. """ Perform a connection test """
  102. def sync(self):
  103. self.command(ESPROM.ESP_SYNC, '\x07\x07\x12\x20' + 32 * '\x55')
  104. for i in xrange(7):
  105. self.command()
  106. """ Try connecting repeatedly until successful, or giving up """
  107. def connect(self):
  108. print 'Connecting...'
  109. for _ in xrange(4):
  110. # issue reset-to-bootloader:
  111. # RTS = either CH_PD or nRESET (both active low = chip in reset)
  112. # DTR = GPIO0 (active low = boot to flasher)
  113. self._port.setDTR(False)
  114. self._port.setRTS(True)
  115. time.sleep(0.05)
  116. self._port.setDTR(True)
  117. self._port.setRTS(False)
  118. time.sleep(0.05)
  119. self._port.setDTR(False)
  120. # worst-case latency timer should be 255ms (probably <20ms)
  121. self._port.timeout = 0.3
  122. for _ in xrange(4):
  123. try:
  124. self._port.flushInput()
  125. self._slip_reader = slip_reader(self._port)
  126. self._port.flushOutput()
  127. self.sync()
  128. self._port.timeout = 5
  129. return
  130. except:
  131. time.sleep(0.05)
  132. raise FatalError('Failed to connect to ESP8266')
  133. """ Read memory address in target """
  134. def read_reg(self, addr):
  135. res = self.command(ESPROM.ESP_READ_REG, struct.pack('<I', addr))
  136. if res[1] != "\0\0":
  137. raise FatalError('Failed to read target memory')
  138. return res[0]
  139. """ Write to memory address in target """
  140. def write_reg(self, addr, value, mask, delay_us=0):
  141. if self.command(ESPROM.ESP_WRITE_REG,
  142. struct.pack('<IIII', addr, value, mask, delay_us))[1] != "\0\0":
  143. raise FatalError('Failed to write target memory')
  144. """ Start downloading an application image to RAM """
  145. def mem_begin(self, size, blocks, blocksize, offset):
  146. if self.command(ESPROM.ESP_MEM_BEGIN,
  147. struct.pack('<IIII', size, blocks, blocksize, offset))[1] != "\0\0":
  148. raise FatalError('Failed to enter RAM download mode')
  149. """ Send a block of an image to RAM """
  150. def mem_block(self, data, seq):
  151. if self.command(ESPROM.ESP_MEM_DATA,
  152. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  153. ESPROM.checksum(data))[1] != "\0\0":
  154. raise FatalError('Failed to write to target RAM')
  155. """ Leave download mode and run the application """
  156. def mem_finish(self, entrypoint=0):
  157. if self.command(ESPROM.ESP_MEM_END,
  158. struct.pack('<II', int(entrypoint == 0), entrypoint))[1] != "\0\0":
  159. raise FatalError('Failed to leave RAM download mode')
  160. """ Start downloading to Flash (performs an erase) """
  161. def flash_begin(self, size, offset):
  162. old_tmo = self._port.timeout
  163. num_blocks = (size + ESPROM.ESP_FLASH_BLOCK - 1) / ESPROM.ESP_FLASH_BLOCK
  164. sectors_per_block = 16
  165. sector_size = self.ESP_FLASH_SECTOR
  166. num_sectors = (size + sector_size - 1) / sector_size
  167. start_sector = offset / sector_size
  168. head_sectors = sectors_per_block - (start_sector % sectors_per_block)
  169. if num_sectors < head_sectors:
  170. head_sectors = num_sectors
  171. if num_sectors < 2 * head_sectors:
  172. erase_size = (num_sectors + 1) / 2 * sector_size
  173. else:
  174. erase_size = (num_sectors - head_sectors) * sector_size
  175. self._port.timeout = 20
  176. t = time.time()
  177. result = self.command(ESPROM.ESP_FLASH_BEGIN,
  178. struct.pack('<IIII', erase_size, num_blocks, ESPROM.ESP_FLASH_BLOCK, offset))[1]
  179. if size != 0:
  180. print "Took %.2fs to erase flash block" % (time.time() - t)
  181. if result != "\0\0":
  182. raise FatalError.WithResult('Failed to enter Flash download mode (result "%s")', result)
  183. self._port.timeout = old_tmo
  184. """ Write block to flash """
  185. def flash_block(self, data, seq):
  186. result = self.command(ESPROM.ESP_FLASH_DATA,
  187. struct.pack('<IIII', len(data), seq, 0, 0) + data,
  188. ESPROM.checksum(data))[1]
  189. if result != "\0\0":
  190. raise FatalError.WithResult('Failed to write to target Flash after seq %d (got result %%s)' % seq, result)
  191. """ Leave flash mode and run/reboot """
  192. def flash_finish(self, reboot=False):
  193. pkt = struct.pack('<I', int(not reboot))
  194. if self.command(ESPROM.ESP_FLASH_END, pkt)[1] != "\0\0":
  195. raise FatalError('Failed to leave Flash mode')
  196. """ Run application code in flash """
  197. def run(self, reboot=False):
  198. # Fake flash begin immediately followed by flash end
  199. self.flash_begin(0, 0)
  200. self.flash_finish(reboot)
  201. """ Read MAC from OTP ROM """
  202. def read_mac(self):
  203. mac0 = self.read_reg(self.ESP_OTP_MAC0)
  204. mac1 = self.read_reg(self.ESP_OTP_MAC1)
  205. mac3 = self.read_reg(self.ESP_OTP_MAC3)
  206. if (mac3 != 0):
  207. oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
  208. elif ((mac1 >> 16) & 0xff) == 0:
  209. oui = (0x18, 0xfe, 0x34)
  210. elif ((mac1 >> 16) & 0xff) == 1:
  211. oui = (0xac, 0xd0, 0x74)
  212. else:
  213. raise FatalError("Unknown OUI")
  214. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  215. """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """
  216. def chip_id(self):
  217. id0 = self.read_reg(self.ESP_OTP_MAC0)
  218. id1 = self.read_reg(self.ESP_OTP_MAC1)
  219. return (id0 >> 24) | ((id1 & 0xffffff) << 8)
  220. """ Read SPI flash manufacturer and device id """
  221. def flash_id(self):
  222. self.flash_begin(0, 0)
  223. self.write_reg(0x60000240, 0x0, 0xffffffff)
  224. self.write_reg(0x60000200, 0x10000000, 0xffffffff)
  225. flash_id = self.read_reg(0x60000240)
  226. self.flash_finish(False)
  227. return flash_id
  228. """ Abuse the loader protocol to force flash to be left in write mode """
  229. def flash_unlock_dio(self):
  230. # Enable flash write mode
  231. self.flash_begin(0, 0)
  232. # Reset the chip rather than call flash_finish(), which would have
  233. # write protected the chip again (why oh why does it do that?!)
  234. self.mem_begin(0,0,0,0x40100000)
  235. self.mem_finish(0x40000080)
  236. """ Perform a chip erase of SPI flash """
  237. def flash_erase(self):
  238. # Trick ROM to initialize SFlash
  239. self.flash_begin(0, 0)
  240. # This is hacky: we don't have a custom stub, instead we trick
  241. # the bootloader to jump to the SPIEraseChip() routine and then halt/crash
  242. # when it tries to boot an unconfigured system.
  243. self.mem_begin(0,0,0,0x40100000)
  244. self.mem_finish(0x40004984)
  245. # Yup - there's no good way to detect if we succeeded.
  246. # It it on the other hand unlikely to fail.
  247. def run_stub(self, stub, params, read_output=True):
  248. stub = dict(stub)
  249. stub['code'] = unhexify(stub['code'])
  250. if 'data' in stub:
  251. stub['data'] = unhexify(stub['data'])
  252. if stub['num_params'] != len(params):
  253. raise FatalError('Stub requires %d params, %d provided'
  254. % (stub['num_params'], len(params)))
  255. params = struct.pack('<' + ('I' * stub['num_params']), *params)
  256. pc = params + stub['code']
  257. # Upload
  258. self.mem_begin(len(pc), 1, len(pc), stub['params_start'])
  259. self.mem_block(pc, 0)
  260. if 'data' in stub:
  261. self.mem_begin(len(stub['data']), 1, len(stub['data']), stub['data_start'])
  262. self.mem_block(stub['data'], 0)
  263. self.mem_finish(stub['entry'])
  264. if read_output:
  265. print 'Stub executed, reading response:'
  266. while True:
  267. p = self.read()
  268. print hexify(p)
  269. if p == '':
  270. return
  271. class ESPBOOTLOADER(object):
  272. """ These are constants related to software ESP bootloader, working with 'v2' image files """
  273. # First byte of the "v2" application image
  274. IMAGE_V2_MAGIC = 0xea
  275. # First 'segment' value in a "v2" application image, appears to be a constant version value?
  276. IMAGE_V2_SEGMENT = 4
  277. def LoadFirmwareImage(filename):
  278. """ Load a firmware image, without knowing what kind of file (v1 or v2) it is.
  279. Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2).
  280. """
  281. with open(filename, 'rb') as f:
  282. magic = ord(f.read(1))
  283. f.seek(0)
  284. if magic == ESPROM.ESP_IMAGE_MAGIC:
  285. return ESPFirmwareImage(f)
  286. elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC:
  287. return OTAFirmwareImage(f)
  288. else:
  289. raise FatalError("Invalid image magic number: %d" % magic)
  290. class BaseFirmwareImage(object):
  291. """ Base class with common firmware image functions """
  292. def __init__(self):
  293. self.segments = []
  294. self.entrypoint = 0
  295. def add_segment(self, addr, data, pad_to=4):
  296. """ Add a segment to the image, with specified address & data
  297. (padded to a boundary of pad_to size) """
  298. # Data should be aligned on word boundary
  299. l = len(data)
  300. if l % pad_to:
  301. data += b"\x00" * (pad_to - l % pad_to)
  302. if l > 0:
  303. self.segments.append((addr, len(data), data))
  304. def load_segment(self, f, is_irom_segment=False):
  305. """ Load the next segment from the image file """
  306. (offset, size) = struct.unpack('<II', f.read(8))
  307. if not is_irom_segment:
  308. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  309. raise FatalError('Suspicious segment 0x%x, length %d' % (offset, size))
  310. segment_data = f.read(size)
  311. if len(segment_data) < size:
  312. raise FatalError('End of file reading segment 0x%x, length %d (actual length %d)' % (offset, size, len(segment_data)))
  313. segment = (offset, size, segment_data)
  314. self.segments.append(segment)
  315. return segment
  316. def save_segment(self, f, segment, checksum=None):
  317. """ Save the next segment to the image file, return next checksum value if provided """
  318. (offset, size, data) = segment
  319. f.write(struct.pack('<II', offset, size))
  320. f.write(data)
  321. if checksum is not None:
  322. return ESPROM.checksum(data, checksum)
  323. def read_checksum(self, f):
  324. """ Return ESPROM checksum from end of just-read image """
  325. # Skip the padding. The checksum is stored in the last byte so that the
  326. # file is a multiple of 16 bytes.
  327. align_file_position(f, 16)
  328. return ord(f.read(1))
  329. def append_checksum(self, f, checksum):
  330. """ Append ESPROM checksum to the just-written image """
  331. align_file_position(f, 16)
  332. f.write(struct.pack('B', checksum))
  333. def write_v1_header(self, f, segments):
  334. f.write(struct.pack('<BBBBI', ESPROM.ESP_IMAGE_MAGIC, len(segments),
  335. self.flash_mode, self.flash_size_freq, self.entrypoint))
  336. class ESPFirmwareImage(BaseFirmwareImage):
  337. """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """
  338. def __init__(self, load_file=None):
  339. super(ESPFirmwareImage, self).__init__()
  340. self.flash_mode = 0
  341. self.flash_size_freq = 0
  342. self.version = 1
  343. if load_file is not None:
  344. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  345. # some sanity check
  346. if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
  347. raise FatalError('Invalid firmware image magic=%d segments=%d' % (magic, segments))
  348. for i in xrange(segments):
  349. self.load_segment(load_file)
  350. self.checksum = self.read_checksum(load_file)
  351. def save(self, filename):
  352. with open(filename, 'wb') as f:
  353. self.write_v1_header(f, self.segments)
  354. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  355. for segment in self.segments:
  356. checksum = self.save_segment(f, segment, checksum)
  357. self.append_checksum(f, checksum)
  358. class OTAFirmwareImage(BaseFirmwareImage):
  359. """ 'Version 2' firmware image, segments loaded by software bootloader stub
  360. (ie Espressif bootloader or rboot)
  361. """
  362. def __init__(self, load_file=None):
  363. super(OTAFirmwareImage, self).__init__()
  364. self.version = 2
  365. if load_file is not None:
  366. (magic, segments, first_flash_mode, first_flash_size_freq, first_entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  367. # some sanity check
  368. if magic != ESPBOOTLOADER.IMAGE_V2_MAGIC:
  369. raise FatalError('Invalid V2 image magic=%d' % (magic))
  370. if segments != 4:
  371. # segment count is not really segment count here, but we expect to see '4'
  372. print 'Warning: V2 header has unexpected "segment" count %d (usually 4)' % segments
  373. # irom segment comes before the second header
  374. self.load_segment(load_file, True)
  375. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', load_file.read(8))
  376. if first_flash_mode != self.flash_mode:
  377. print('WARNING: Flash mode value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  378. % (first_flash_mode, self.flash_mode))
  379. if first_flash_size_freq != self.flash_size_freq:
  380. print('WARNING: Flash size/freq value in first header (0x%02x) disagrees with second (0x%02x). Using second value.'
  381. % (first_flash_size_freq, self.flash_size_freq))
  382. if first_entrypoint != self.entrypoint:
  383. print('WARNING: Enterypoint address in first header (0x%08x) disagrees with second header (0x%08x). Using second value.'
  384. % (first_entrypoint, self.entrypoint))
  385. if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
  386. raise FatalError('Invalid V2 second header magic=%d segments=%d' % (magic, segments))
  387. # load all the usual segments
  388. for _ in xrange(segments):
  389. self.load_segment(load_file)
  390. self.checksum = self.read_checksum(load_file)
  391. def save(self, filename):
  392. with open(filename, 'wb') as f:
  393. # Save first header for irom0 segment
  394. f.write(struct.pack('<BBBBI', ESPBOOTLOADER.IMAGE_V2_MAGIC, ESPBOOTLOADER.IMAGE_V2_SEGMENT,
  395. self.flash_mode, self.flash_size_freq, self.entrypoint))
  396. # irom0 segment identified by load address zero
  397. irom_segments = [segment for segment in self.segments if segment[0] == 0]
  398. if len(irom_segments) != 1:
  399. raise FatalError('Found %d segments that could be irom0. Bad ELF file?' % len(irom_segments))
  400. # save irom0 segment
  401. irom_segment = irom_segments[0]
  402. self.save_segment(f, irom_segment)
  403. # second header, matches V1 header and contains loadable segments
  404. normal_segments = [s for s in self.segments if s != irom_segment]
  405. self.write_v1_header(f, normal_segments)
  406. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  407. for segment in normal_segments:
  408. checksum = self.save_segment(f, segment, checksum)
  409. self.append_checksum(f, checksum)
  410. class ELFFile(object):
  411. def __init__(self, name):
  412. self.name = binutils_safe_path(name)
  413. self.symbols = None
  414. def _fetch_symbols(self):
  415. if self.symbols is not None:
  416. return
  417. self.symbols = {}
  418. try:
  419. tool_nm = "xtensa-lx106-elf-nm"
  420. if os.getenv('XTENSA_CORE') == 'lx106':
  421. tool_nm = "xt-nm"
  422. proc = subprocess.Popen([tool_nm, self.name], stdout=subprocess.PIPE)
  423. except OSError:
  424. print "Error calling %s, do you have Xtensa toolchain in PATH?" % tool_nm
  425. sys.exit(1)
  426. for l in proc.stdout:
  427. fields = l.strip().split()
  428. try:
  429. if fields[0] == "U":
  430. print "Warning: ELF binary has undefined symbol %s" % fields[1]
  431. continue
  432. if fields[0] == "w":
  433. continue # can skip weak symbols
  434. self.symbols[fields[2]] = int(fields[0], 16)
  435. except ValueError:
  436. raise FatalError("Failed to strip symbol output from nm: %s" % fields)
  437. def get_symbol_addr(self, sym):
  438. self._fetch_symbols()
  439. return self.symbols[sym]
  440. def get_entry_point(self):
  441. tool_readelf = "xtensa-lx106-elf-readelf"
  442. if os.getenv('XTENSA_CORE') == 'lx106':
  443. tool_readelf = "xt-readelf"
  444. try:
  445. proc = subprocess.Popen([tool_readelf, "-h", self.name], stdout=subprocess.PIPE)
  446. except OSError:
  447. print "Error calling %s, do you have Xtensa toolchain in PATH?" % tool_readelf
  448. sys.exit(1)
  449. for l in proc.stdout:
  450. fields = l.strip().split()
  451. if fields[0] == "Entry":
  452. return int(fields[3], 0)
  453. def load_section(self, section):
  454. tool_objcopy = "xtensa-lx106-elf-objcopy"
  455. if os.getenv('XTENSA_CORE') == 'lx106':
  456. tool_objcopy = "xt-objcopy"
  457. tmpsection = binutils_safe_path(tempfile.mktemp(suffix=".section"))
  458. try:
  459. subprocess.check_call([tool_objcopy, "--only-section", section, "-Obinary", self.name, tmpsection])
  460. with open(tmpsection, "rb") as f:
  461. data = f.read()
  462. finally:
  463. os.remove(tmpsection)
  464. return data
  465. class CesantaFlasher(object):
  466. # From stub_flasher.h
  467. CMD_FLASH_WRITE = 1
  468. CMD_FLASH_READ = 2
  469. CMD_FLASH_DIGEST = 3
  470. CMD_BOOT_FW = 6
  471. def __init__(self, esp, baud_rate=0):
  472. print 'Running Cesanta flasher stub...'
  473. if baud_rate <= ESPROM.ESP_ROM_BAUD: # don't change baud rates if we already synced at that rate
  474. baud_rate = 0
  475. self._esp = esp
  476. esp.run_stub(json.loads(_CESANTA_FLASHER_STUB), [baud_rate], read_output=False)
  477. if baud_rate > 0:
  478. esp._port.baudrate = baud_rate
  479. # Read the greeting.
  480. p = esp.read()
  481. if p != 'OHAI':
  482. raise FatalError('Failed to connect to the flasher (got %s)' % hexify(p))
  483. def flash_write(self, addr, data, show_progress=False):
  484. assert addr % self._esp.ESP_FLASH_SECTOR == 0, 'Address must be sector-aligned'
  485. assert len(data) % self._esp.ESP_FLASH_SECTOR == 0, 'Length must be sector-aligned'
  486. sys.stdout.write('Writing %d @ 0x%x... ' % (len(data), addr))
  487. sys.stdout.flush()
  488. self._esp.write(struct.pack('<B', self.CMD_FLASH_WRITE))
  489. self._esp.write(struct.pack('<III', addr, len(data), 1))
  490. num_sent, num_written = 0, 0
  491. while num_written < len(data):
  492. p = self._esp.read()
  493. if len(p) == 4:
  494. num_written = struct.unpack('<I', p)[0]
  495. elif len(p) == 1:
  496. status_code = struct.unpack('<B', p)[0]
  497. raise FatalError('Write failure, status: %x' % status_code)
  498. else:
  499. raise FatalError('Unexpected packet while writing: %s' % hexify(p))
  500. if show_progress:
  501. progress = '%d (%d %%)' % (num_written, num_written * 100.0 / len(data))
  502. sys.stdout.write(progress + '\b' * len(progress))
  503. sys.stdout.flush()
  504. while num_sent - num_written < 5120:
  505. self._esp._port.write(data[num_sent:num_sent + 1024])
  506. num_sent += 1024
  507. p = self._esp.read()
  508. if len(p) != 16:
  509. raise FatalError('Expected digest, got: %s' % hexify(p))
  510. digest = hexify(p).upper()
  511. expected_digest = hashlib.md5(data).hexdigest().upper()
  512. print
  513. if digest != expected_digest:
  514. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  515. p = self._esp.read()
  516. if len(p) != 1:
  517. raise FatalError('Expected status, got: %s' % hexify(p))
  518. status_code = struct.unpack('<B', p)[0]
  519. if status_code != 0:
  520. raise FatalError('Write failure, status: %x' % status_code)
  521. def flash_read(self, addr, length, show_progress=False):
  522. sys.stdout.write('Reading %d @ 0x%x... ' % (length, addr))
  523. sys.stdout.flush()
  524. self._esp.write(struct.pack('<B', self.CMD_FLASH_READ))
  525. # USB may not be able to keep up with the read rate, especially at
  526. # higher speeds. Since we don't have flow control, this will result in
  527. # data loss. Hence, we use small packet size and only allow small
  528. # number of bytes in flight, which we can reasonably expect to fit in
  529. # the on-chip FIFO. max_in_flight = 64 works for CH340G, other chips may
  530. # have longer FIFOs and could benefit from increasing max_in_flight.
  531. self._esp.write(struct.pack('<IIII', addr, length, 32, 64))
  532. data = ''
  533. while True:
  534. p = self._esp.read()
  535. data += p
  536. self._esp.write(struct.pack('<I', len(data)))
  537. if show_progress and (len(data) % 1024 == 0 or len(data) == length):
  538. progress = '%d (%d %%)' % (len(data), len(data) * 100.0 / length)
  539. sys.stdout.write(progress + '\b' * len(progress))
  540. sys.stdout.flush()
  541. if len(data) == length:
  542. break
  543. if len(data) > length:
  544. raise FatalError('Read more than expected')
  545. p = self._esp.read()
  546. if len(p) != 16:
  547. raise FatalError('Expected digest, got: %s' % hexify(p))
  548. expected_digest = hexify(p).upper()
  549. digest = hashlib.md5(data).hexdigest().upper()
  550. print
  551. if digest != expected_digest:
  552. raise FatalError('Digest mismatch: expected %s, got %s' % (expected_digest, digest))
  553. p = self._esp.read()
  554. if len(p) != 1:
  555. raise FatalError('Expected status, got: %s' % hexify(p))
  556. status_code = struct.unpack('<B', p)[0]
  557. if status_code != 0:
  558. raise FatalError('Write failure, status: %x' % status_code)
  559. return data
  560. def flash_digest(self, addr, length, digest_block_size=0):
  561. self._esp.write(struct.pack('<B', self.CMD_FLASH_DIGEST))
  562. self._esp.write(struct.pack('<III', addr, length, digest_block_size))
  563. digests = []
  564. while True:
  565. p = self._esp.read()
  566. if len(p) == 16:
  567. digests.append(p)
  568. elif len(p) == 1:
  569. status_code = struct.unpack('<B', p)[0]
  570. if status_code != 0:
  571. raise FatalError('Write failure, status: %x' % status_code)
  572. break
  573. else:
  574. raise FatalError('Unexpected packet: %s' % hexify(p))
  575. return digests[-1], digests[:-1]
  576. def boot_fw(self):
  577. self._esp.write(struct.pack('<B', self.CMD_BOOT_FW))
  578. p = self._esp.read()
  579. if len(p) != 1:
  580. raise FatalError('Expected status, got: %s' % hexify(p))
  581. status_code = struct.unpack('<B', p)[0]
  582. if status_code != 0:
  583. raise FatalError('Boot failure, status: %x' % status_code)
  584. def slip_reader(port):
  585. """Generator to read SLIP packets from a serial port.
  586. Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
  587. Designed to avoid too many calls to serial.read(1), which can bog
  588. down on slow systems.
  589. """
  590. partial_packet = None
  591. in_escape = False
  592. while True:
  593. waiting = port.inWaiting()
  594. read_bytes = port.read(1 if waiting == 0 else waiting)
  595. if read_bytes == '':
  596. raise FatalError("Timed out waiting for packet %s" % ("header" if partial_packet is None else "content"))
  597. for b in read_bytes:
  598. if partial_packet is None: # waiting for packet header
  599. if b == '\xc0':
  600. partial_packet = ""
  601. else:
  602. raise FatalError('Invalid head of packet (%r)' % b)
  603. elif in_escape: # part-way through escape sequence
  604. in_escape = False
  605. if b == '\xdc':
  606. partial_packet += '\xc0'
  607. elif b == '\xdd':
  608. partial_packet += '\xdb'
  609. else:
  610. raise FatalError('Invalid SLIP escape (%r%r)' % ('\xdb', b))
  611. elif b == '\xdb': # start of escape sequence
  612. in_escape = True
  613. elif b == '\xc0': # end of packet
  614. yield partial_packet
  615. partial_packet = None
  616. else: # normal byte in packet
  617. partial_packet += b
  618. def arg_auto_int(x):
  619. return int(x, 0)
  620. def div_roundup(a, b):
  621. """ Return a/b rounded up to nearest integer,
  622. equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
  623. without possible floating point accuracy errors.
  624. """
  625. return (int(a) + int(b) - 1) / int(b)
  626. def binutils_safe_path(p):
  627. """Returns a 'safe' version of path 'p' to pass to binutils
  628. Only does anything under Cygwin Python, where cygwin paths need to
  629. be translated to Windows paths if the binutils wasn't compiled
  630. using Cygwin (should also work with binutils compiled using
  631. Cygwin, see #73.)
  632. """
  633. if sys.platform == "cygwin":
  634. try:
  635. return subprocess.check_output(["cygpath", "-w", p]).rstrip('\n')
  636. except subprocess.CalledProcessError:
  637. print "WARNING: Failed to call cygpath to sanitise Cygwin path."
  638. return p
  639. def align_file_position(f, size):
  640. """ Align the position in the file to the next block of specified size """
  641. align = (size - 1) - (f.tell() % size)
  642. f.seek(align, 1)
  643. def hexify(s):
  644. return ''.join('%02X' % ord(c) for c in s)
  645. def unhexify(hs):
  646. s = ''
  647. for i in range(0, len(hs) - 1, 2):
  648. s += chr(int(hs[i] + hs[i + 1], 16))
  649. return s
  650. class FatalError(RuntimeError):
  651. """
  652. Wrapper class for runtime errors that aren't caused by internal bugs, but by
  653. ESP8266 responses or input content.
  654. """
  655. def __init__(self, message):
  656. RuntimeError.__init__(self, message)
  657. @staticmethod
  658. def WithResult(message, result):
  659. """
  660. Return a fatal error object that includes the hex values of
  661. 'result' as a string formatted argument.
  662. """
  663. return FatalError(message % ", ".join(hex(ord(x)) for x in result))
  664. # "Operation" commands, executable at command line. One function each
  665. #
  666. # Each function takes either two args (<ESPROM instance>, <args>) or a single <args>
  667. # argument.
  668. def load_ram(esp, args):
  669. image = LoadFirmwareImage(args.filename)
  670. print 'RAM boot...'
  671. for (offset, size, data) in image.segments:
  672. print 'Downloading %d bytes at %08x...' % (size, offset),
  673. sys.stdout.flush()
  674. esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset)
  675. seq = 0
  676. while len(data) > 0:
  677. esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
  678. data = data[esp.ESP_RAM_BLOCK:]
  679. seq += 1
  680. print 'done!'
  681. print 'All segments done, executing at %08x' % image.entrypoint
  682. esp.mem_finish(image.entrypoint)
  683. def read_mem(esp, args):
  684. print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address))
  685. def write_mem(esp, args):
  686. esp.write_reg(args.address, args.value, args.mask, 0)
  687. print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address)
  688. def dump_mem(esp, args):
  689. f = file(args.filename, 'wb')
  690. for i in xrange(args.size / 4):
  691. d = esp.read_reg(args.address + (i * 4))
  692. f.write(struct.pack('<I', d))
  693. if f.tell() % 1024 == 0:
  694. print '\r%d bytes read... (%d %%)' % (f.tell(),
  695. f.tell() * 100 / args.size),
  696. sys.stdout.flush()
  697. print 'Done!'
  698. def write_flash(esp, args):
  699. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  700. flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70, '64m':0x80, '128m':0x90}[args.flash_size]
  701. flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  702. flash_params = struct.pack('BB', flash_mode, flash_size_freq)
  703. flasher = CesantaFlasher(esp, args.baud)
  704. for address, argfile in args.addr_filename:
  705. image = argfile.read()
  706. argfile.seek(0) # rewind in case we need it again
  707. # Fix sflash config data.
  708. if address == 0 and image[0] == '\xe9':
  709. print 'Flash params set to 0x%02x%02x' % (flash_mode, flash_size_freq)
  710. image = image[0:2] + flash_params + image[4:]
  711. # Pad to sector size, which is the minimum unit of writing (erasing really).
  712. if len(image) % esp.ESP_FLASH_SECTOR != 0:
  713. image += '\xff' * (esp.ESP_FLASH_SECTOR - (len(image) % esp.ESP_FLASH_SECTOR))
  714. t = time.time()
  715. flasher.flash_write(address, image, not args.no_progress)
  716. t = time.time() - t
  717. print ('\rWrote %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  718. % (len(image), address, t, len(image) / t * 8 / 1000))
  719. print 'Leaving...'
  720. if args.verify:
  721. print 'Verifying just-written flash...'
  722. _verify_flash(flasher, args, flash_params)
  723. flasher.boot_fw()
  724. def image_info(args):
  725. image = LoadFirmwareImage(args.filename)
  726. print('Image version: %d' % image.version)
  727. print('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set'
  728. print '%d segments' % len(image.segments)
  729. print
  730. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  731. for (idx, (offset, size, data)) in enumerate(image.segments):
  732. if image.version == 2 and idx == 0:
  733. print 'Segment 1: %d bytes IROM0 (no load address)' % size
  734. else:
  735. print 'Segment %d: %5d bytes at %08x' % (idx + 1, size, offset)
  736. checksum = ESPROM.checksum(data, checksum)
  737. print
  738. print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!')
  739. def make_image(args):
  740. image = ESPFirmwareImage()
  741. if len(args.segfile) == 0:
  742. raise FatalError('No segments specified')
  743. if len(args.segfile) != len(args.segaddr):
  744. raise FatalError('Number of specified files does not match number of specified addresses')
  745. for (seg, addr) in zip(args.segfile, args.segaddr):
  746. data = file(seg, 'rb').read()
  747. image.add_segment(addr, data)
  748. image.entrypoint = args.entrypoint
  749. image.save(args.output)
  750. def elf2image(args):
  751. e = ELFFile(args.input)
  752. if args.version == '1':
  753. image = ESPFirmwareImage()
  754. else:
  755. image = OTAFirmwareImage()
  756. irom_data = e.load_section('.irom0.text')
  757. if len(irom_data) == 0:
  758. raise FatalError(".irom0.text section not found in ELF file - can't create V2 image.")
  759. image.add_segment(0, irom_data, 16)
  760. image.entrypoint = e.get_entry_point()
  761. for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")):
  762. data = e.load_section(section)
  763. image.add_segment(e.get_symbol_addr(start), data)
  764. image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  765. image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40, '16m-c1': 0x50, '32m-c1':0x60, '32m-c2':0x70, '64m':0x80, '128m':0x90}[args.flash_size]
  766. image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  767. irom_offs = e.get_symbol_addr("_irom0_text_start") - 0x40200000
  768. if args.version == '1':
  769. if args.output is None:
  770. args.output = args.input + '-'
  771. image.save(args.output + "0x00000.bin")
  772. data = e.load_section(".irom0.text")
  773. if irom_offs < 0:
  774. raise FatalError('Address of symbol _irom0_text_start in ELF is located before flash mapping address. Bad linker script?')
  775. if (irom_offs & 0xFFF) != 0: # irom0 isn't flash sector aligned
  776. print "WARNING: irom0 section offset is 0x%08x. ELF is probably linked for 'elf2image --version=2'" % irom_offs
  777. with open(args.output + "0x%05x.bin" % irom_offs, "wb") as f:
  778. f.write(data)
  779. f.close()
  780. else: # V2 OTA image
  781. if args.output is None:
  782. args.output = "%s-0x%05x.bin" % (os.path.splitext(args.input)[0], irom_offs & ~(ESPROM.ESP_FLASH_SECTOR - 1))
  783. image.save(args.output)
  784. def read_mac(esp, args):
  785. mac = esp.read_mac()
  786. print 'MAC: %s' % ':'.join(map(lambda x: '%02x' % x, mac))
  787. def chip_id(esp, args):
  788. chipid = esp.chip_id()
  789. print 'Chip ID: 0x%08x' % chipid
  790. def erase_flash(esp, args):
  791. print 'Erasing flash (this may take a while)...'
  792. esp.flash_erase()
  793. def run(esp, args):
  794. esp.run()
  795. def flash_id(esp, args):
  796. flash_id = esp.flash_id()
  797. print 'Manufacturer: %02x' % (flash_id & 0xff)
  798. print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff)
  799. def read_flash(esp, args):
  800. flasher = CesantaFlasher(esp, args.baud)
  801. t = time.time()
  802. data = flasher.flash_read(args.address, args.size, not args.no_progress)
  803. t = time.time() - t
  804. print ('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...'
  805. % (len(data), args.address, t, len(data) / t * 8 / 1000))
  806. file(args.filename, 'wb').write(data)
  807. def _verify_flash(flasher, args, flash_params=None):
  808. differences = False
  809. for address, argfile in args.addr_filename:
  810. image = argfile.read()
  811. argfile.seek(0) # rewind in case we need it again
  812. if address == 0 and image[0] == '\xe9' and flash_params is not None:
  813. image = image[0:2] + flash_params + image[4:]
  814. image_size = len(image)
  815. print 'Verifying 0x%x (%d) bytes @ 0x%08x in flash against %s...' % (image_size, image_size, address, argfile.name)
  816. # Try digest first, only read if there are differences.
  817. digest, _ = flasher.flash_digest(address, image_size)
  818. digest = hexify(digest).upper()
  819. expected_digest = hashlib.md5(image).hexdigest().upper()
  820. if digest == expected_digest:
  821. print '-- verify OK (digest matched)'
  822. continue
  823. else:
  824. differences = True
  825. if getattr(args, 'diff', 'no') != 'yes':
  826. print '-- verify FAILED (digest mismatch)'
  827. continue
  828. flash = flasher.flash_read(address, image_size)
  829. assert flash != image
  830. diff = [i for i in xrange(image_size) if flash[i] != image[i]]
  831. print '-- verify FAILED: %d differences, first @ 0x%08x' % (len(diff), address + diff[0])
  832. for d in diff:
  833. print ' %08x %02x %02x' % (address + d, ord(flash[d]), ord(image[d]))
  834. if differences:
  835. raise FatalError("Verify failed.")
  836. def verify_flash(esp, args, flash_params=None):
  837. flasher = CesantaFlasher(esp)
  838. _verify_flash(flasher, args, flash_params)
  839. def version(args):
  840. print __version__
  841. #
  842. # End of operations functions
  843. #
  844. def main():
  845. parser = argparse.ArgumentParser(description='esptool.py v%s - ESP8266 ROM Bootloader Utility' % __version__, prog='esptool')
  846. parser.add_argument(
  847. '--port', '-p',
  848. help='Serial port device',
  849. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0'))
  850. parser.add_argument(
  851. '--baud', '-b',
  852. help='Serial port baud rate used when flashing/reading',
  853. type=arg_auto_int,
  854. default=os.environ.get('ESPTOOL_BAUD', ESPROM.ESP_ROM_BAUD))
  855. subparsers = parser.add_subparsers(
  856. dest='operation',
  857. help='Run esptool {command} -h for additional help')
  858. parser_load_ram = subparsers.add_parser(
  859. 'load_ram',
  860. help='Download an image to RAM and execute')
  861. parser_load_ram.add_argument('filename', help='Firmware image')
  862. parser_dump_mem = subparsers.add_parser(
  863. 'dump_mem',
  864. help='Dump arbitrary memory to disk')
  865. parser_dump_mem.add_argument('address', help='Base address', type=arg_auto_int)
  866. parser_dump_mem.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  867. parser_dump_mem.add_argument('filename', help='Name of binary dump')
  868. parser_read_mem = subparsers.add_parser(
  869. 'read_mem',
  870. help='Read arbitrary memory location')
  871. parser_read_mem.add_argument('address', help='Address to read', type=arg_auto_int)
  872. parser_write_mem = subparsers.add_parser(
  873. 'write_mem',
  874. help='Read-modify-write to arbitrary memory location')
  875. parser_write_mem.add_argument('address', help='Address to write', type=arg_auto_int)
  876. parser_write_mem.add_argument('value', help='Value', type=arg_auto_int)
  877. parser_write_mem.add_argument('mask', help='Mask of bits to write', type=arg_auto_int)
  878. def add_spi_flash_subparsers(parent):
  879. """ Add common parser arguments for SPI flash properties """
  880. parent.add_argument('--flash_freq', '-ff', help='SPI Flash frequency',
  881. choices=['40m', '26m', '20m', '80m'],
  882. default=os.environ.get('ESPTOOL_FF', '40m'))
  883. parent.add_argument('--flash_mode', '-fm', help='SPI Flash mode',
  884. choices=['qio', 'qout', 'dio', 'dout'],
  885. default=os.environ.get('ESPTOOL_FM', 'qio'))
  886. parent.add_argument('--flash_size', '-fs', help='SPI Flash size in Mbit', type=str.lower,
  887. choices=['4m', '2m', '8m', '16m', '32m', '16m-c1', '32m-c1', '32m-c2', '64m', '128m'],
  888. default=os.environ.get('ESPTOOL_FS', '4m'))
  889. parser_write_flash = subparsers.add_parser(
  890. 'write_flash',
  891. help='Write a binary blob to flash')
  892. parser_write_flash.add_argument('addr_filename', metavar='<address> <filename>', help='Address followed by binary filename, separated by space',
  893. action=AddrFilenamePairAction)
  894. add_spi_flash_subparsers(parser_write_flash)
  895. parser_write_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  896. parser_write_flash.add_argument('--verify', help='Verify just-written data (only necessary if very cautious, data is already CRCed', action='store_true')
  897. subparsers.add_parser(
  898. 'run',
  899. help='Run application code in flash')
  900. parser_image_info = subparsers.add_parser(
  901. 'image_info',
  902. help='Dump headers from an application image')
  903. parser_image_info.add_argument('filename', help='Image file to parse')
  904. parser_make_image = subparsers.add_parser(
  905. 'make_image',
  906. help='Create an application image from binary files')
  907. parser_make_image.add_argument('output', help='Output image file')
  908. parser_make_image.add_argument('--segfile', '-f', action='append', help='Segment input file')
  909. parser_make_image.add_argument('--segaddr', '-a', action='append', help='Segment base address', type=arg_auto_int)
  910. parser_make_image.add_argument('--entrypoint', '-e', help='Address of entry point', type=arg_auto_int, default=0)
  911. parser_elf2image = subparsers.add_parser(
  912. 'elf2image',
  913. help='Create an application image from ELF file')
  914. parser_elf2image.add_argument('input', help='Input ELF file')
  915. parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str)
  916. parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1')
  917. add_spi_flash_subparsers(parser_elf2image)
  918. subparsers.add_parser(
  919. 'read_mac',
  920. help='Read MAC address from OTP ROM')
  921. subparsers.add_parser(
  922. 'chip_id',
  923. help='Read Chip ID from OTP ROM')
  924. subparsers.add_parser(
  925. 'flash_id',
  926. help='Read SPI flash manufacturer and device ID')
  927. parser_read_flash = subparsers.add_parser(
  928. 'read_flash',
  929. help='Read SPI flash content')
  930. parser_read_flash.add_argument('address', help='Start address', type=arg_auto_int)
  931. parser_read_flash.add_argument('size', help='Size of region to dump', type=arg_auto_int)
  932. parser_read_flash.add_argument('filename', help='Name of binary dump')
  933. parser_read_flash.add_argument('--no-progress', '-p', help='Suppress progress output', action="store_true")
  934. parser_verify_flash = subparsers.add_parser(
  935. 'verify_flash',
  936. help='Verify a binary blob against flash')
  937. parser_verify_flash.add_argument('addr_filename', help='Address and binary file to verify there, separated by space',
  938. action=AddrFilenamePairAction)
  939. parser_verify_flash.add_argument('--diff', '-d', help='Show differences',
  940. choices=['no', 'yes'], default='no')
  941. subparsers.add_parser(
  942. 'erase_flash',
  943. help='Perform Chip Erase on SPI flash')
  944. subparsers.add_parser(
  945. 'version', help='Print esptool version')
  946. # internal sanity check - every operation matches a module function of the same name
  947. for operation in subparsers.choices.keys():
  948. assert operation in globals(), "%s should be a module function" % operation
  949. args = parser.parse_args()
  950. print 'esptool.py v%s' % __version__
  951. # operation function can take 1 arg (args), 2 args (esp, arg)
  952. # or be a member function of the ESPROM class.
  953. operation_func = globals()[args.operation]
  954. operation_args,_,_,_ = inspect.getargspec(operation_func)
  955. if operation_args[0] == 'esp': # operation function takes an ESPROM connection object
  956. initial_baud = min(ESPROM.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate
  957. esp = ESPROM(args.port, initial_baud)
  958. esp.connect()
  959. operation_func(esp, args)
  960. else:
  961. operation_func(args)
  962. class AddrFilenamePairAction(argparse.Action):
  963. """ Custom parser class for the address/filename pairs passed as arguments """
  964. def __init__(self, option_strings, dest, nargs='+', **kwargs):
  965. super(AddrFilenamePairAction, self).__init__(option_strings, dest, nargs, **kwargs)
  966. def __call__(self, parser, namespace, values, option_string=None):
  967. # validate pair arguments
  968. pairs = []
  969. for i in range(0,len(values),2):
  970. try:
  971. address = int(values[i],0)
  972. except ValueError as e:
  973. raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i])
  974. try:
  975. argfile = open(values[i + 1], 'rb')
  976. except IOError as e:
  977. raise argparse.ArgumentError(self, e)
  978. except IndexError:
  979. raise argparse.ArgumentError(self,'Must be pairs of an address and the binary filename to write there')
  980. pairs.append((address, argfile))
  981. setattr(namespace, self.dest, pairs)
  982. # This is "wrapped" stub_flasher.c, to be loaded using run_stub.
  983. _CESANTA_FLASHER_STUB = """\
  984. {"code_start": 1074790404, "code": "080000601C000060000000601000006031FCFF71FCFF\
  985. 81FCFFC02000680332D218C020004807404074DCC48608005823C0200098081BA5A9239245005803\
  986. 1B555903582337350129230B446604DFC6F3FF21EEFFC0200069020DF0000000010078480040004A\
  987. 0040B449004012C1F0C921D911E901DD0209312020B4ED033C2C56C2073020B43C3C56420701F5FF\
  988. C000003C4C569206CD0EEADD860300202C4101F1FFC0000056A204C2DCF0C02DC0CC6CCAE2D1EAFF\
  989. 0606002030F456D3FD86FBFF00002020F501E8FFC00000EC82D0CCC0C02EC0C73DEB2ADC46030020\
  990. 2C4101E1FFC00000DC42C2DCF0C02DC056BCFEC602003C5C8601003C6C4600003C7C08312D0CD811\
  991. C821E80112C1100DF0000C180000140010400C0000607418000064180000801800008C1800008418\
  992. 0000881800009018000018980040880F0040A80F0040349800404C4A0040740F0040800F0040980F\
  993. 00400099004012C1E091F5FFC961CD0221EFFFE941F9310971D9519011C01A223902E2D1180C0222\
  994. 6E1D21E4FF31E9FF2AF11A332D0F42630001EAFFC00000C030B43C2256A31621E1FF1A2228022030\
  995. B43C3256B31501ADFFC00000DD023C4256ED1431D6FF4D010C52D90E192E126E0101DDFFC0000021\
  996. D2FF32A101C020004802303420C0200039022C0201D7FFC00000463300000031CDFF1A333803D023\
  997. C03199FF27B31ADC7F31CBFF1A3328030198FFC0000056C20E2193FF2ADD060E000031C6FF1A3328\
  998. 030191FFC0000056820DD2DD10460800000021BEFF1A2228029CE231BCFFC020F51A33290331BBFF\
  999. C02C411A332903C0F0F4222E1D22D204273D9332A3FFC02000280E27B3F721ABFF381E1A2242A400\
  1000. 01B5FFC00000381E2D0C42A40001B3FFC0000056120801B2FFC00000C02000280EC2DC0422D2FCC0\
  1001. 2000290E01ADFFC00000222E1D22D204226E1D281E22D204E7B204291E860000126E012198FF32A0\
  1002. 042A21C54C003198FF222E1D1A33380337B202C6D6FF2C02019FFFC000002191FF318CFF1A223A31\
  1003. 019CFFC00000218DFF1C031A22C549000C02060300003C528601003C624600003C72918BFF9A1108\
  1004. 71C861D851E841F83112C1200DF00010000068100000581000007010000074100000781000007C10\
  1005. 0000801000001C4B0040803C004091FDFF12C1E061F7FFC961E941F9310971D9519011C01A662906\
  1006. 21F3FFC2D1101A22390231F2FF0C0F1A33590331EAFFF26C1AED045C2247B3028636002D0C016DFF\
  1007. C0000021E5FF41EAFF2A611A4469040622000021E4FF1A222802F0D2C0D7BE01DD0E31E0FF4D0D1A\
  1008. 3328033D0101E2FFC00000561209D03D2010212001DFFFC000004D0D2D0C3D01015DFFC0000041D5\
  1009. FFDAFF1A444804D0648041D2FF1A4462640061D1FF106680622600673F1331D0FF10338028030C43\
  1010. 853A002642164613000041CAFF222C1A1A444804202FC047328006F6FF222C1A273F3861C2FF222C\
  1011. 1A1A6668066732B921BDFF3D0C1022800148FFC0000021BAFF1C031A2201BFFFC000000C02460300\
  1012. 5C3206020000005C424600005C5291B7FF9A110871C861D851E841F83112C1200DF0B0100000C010\
  1013. 0000D010000012C1E091FEFFC961D951E9410971F931CD039011C0ED02DD0431A1FF9C1422A06247\
  1014. B302062D0021F4FF1A22490286010021F1FF1A223902219CFF2AF12D0F011FFFC00000461C0022D1\
  1015. 10011CFFC0000021E9FFFD0C1A222802C7B20621E6FF1A22F8022D0E3D014D0F0195FFC000008C52\
  1016. 22A063C6180000218BFF3D01102280F04F200111FFC00000AC7D22D1103D014D0F010DFFC0000021\
  1017. D6FF32D110102280010EFFC0000021D3FF1C031A220185FFC00000FAEEF0CCC056ACF821CDFF317A\
  1018. FF1A223A310105FFC0000021C9FF1C031A22017CFFC000002D0C91C8FF9A110871C861D851E841F8\
  1019. 3112C1200DF0000200600000001040020060FFFFFF0012C1E00C02290131FAFF21FAFF026107C961\
  1020. C02000226300C02000C80320CC10564CFF21F5FFC02000380221F4FF20231029010C432D010163FF\
  1021. C0000008712D0CC86112C1200DF00080FE3F8449004012C1D0C9A109B17CFC22C1110C13C51C0026\
  1022. 1202463000220111C24110B68202462B0031F5FF3022A02802A002002D011C03851A0066820A2801\
  1023. 32210105A6FF0607003C12C60500000010212032A01085180066A20F2221003811482105B3FF2241\
  1024. 10861A004C1206FDFF2D011C03C5160066B20E280138114821583185CFFF06F7FF005C1286F5FF00\
  1025. 10212032A01085140066A20D2221003811482105E1FF06EFFF0022A06146EDFF45F0FFC6EBFF0000\
  1026. 01D2FFC0000006E9FF000C022241100C1322C110C50F00220111060600000022C1100C13C50E0022\
  1027. 011132C2FA303074B6230206C8FF08B1C8A112C1300DF0000000000010404F484149007519031027\
  1028. 000000110040A8100040BC0F0040583F0040CC2E00401CE20040D83900408000004021F4FF12C1E0\
  1029. C961C80221F2FF097129010C02D951C91101F4FFC0000001F3FFC00000AC2C22A3E801F2FFC00000\
  1030. 21EAFFC031412A233D0C01EFFFC000003D0222A00001EDFFC00000C1E4FF2D0C01E8FFC000002D01\
  1031. 32A004450400C5E7FFDD022D0C01E3FFC00000666D1F4B2131DCFF4600004B22C0200048023794F5\
  1032. 31D9FFC0200039023DF08601000001DCFFC000000871C861D85112C1200DF000000012C1F0026103\
  1033. 01EAFEC00000083112C1100DF000643B004012C1D0E98109B1C9A1D991F97129013911E2A0C001FA\
  1034. FFC00000CD02E792F40C0DE2A0C0F2A0DB860D00000001F4FFC00000204220E71240F7921C226102\
  1035. 01EFFFC0000052A0DC482157120952A0DD571205460500004D0C3801DA234242001BDD3811379DC5\
  1036. C6000000000C0DC2A0C001E3FFC00000C792F608B12D0DC8A1D891E881F87112C1300DF00000", "\
  1037. entry": 1074792180, "num_params": 1, "params_start": 1074790400, "data": "FE0510\
  1038. 401A0610403B0610405A0610407A061040820610408C0610408C061040", "data_start": 10736\
  1039. 43520}
  1040. """
  1041. if __name__ == '__main__':
  1042. try:
  1043. main()
  1044. except FatalError as e:
  1045. print '\nA fatal error occurred: %s' % e
  1046. sys.exit(2)