esptool.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. #!/usr/bin/env python
  2. #
  3. # ESP8266 ROM Bootloader Utility
  4. # https://github.com/themadinventor/esptool
  5. #
  6. # Copyright (C) 2014 Fredrik Ahlberg
  7. #
  8. # This program is free software; you can redistribute it and/or modify it under
  9. # the terms of the GNU General Public License as published by the Free Software
  10. # Foundation; either version 2 of the License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful, but WITHOUT
  13. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License along with
  17. # this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  18. # Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. import sys
  20. import struct
  21. import serial
  22. import math
  23. import time
  24. import argparse
  25. import os
  26. import subprocess
  27. class ESPROM:
  28. # These are the currently known commands supported by the ROM
  29. ESP_FLASH_BEGIN = 0x02
  30. ESP_FLASH_DATA = 0x03
  31. ESP_FLASH_END = 0x04
  32. ESP_MEM_BEGIN = 0x05
  33. ESP_MEM_END = 0x06
  34. ESP_MEM_DATA = 0x07
  35. ESP_SYNC = 0x08
  36. ESP_WRITE_REG = 0x09
  37. ESP_READ_REG = 0x0a
  38. # Maximum block sized for RAM and Flash writes, respectively.
  39. ESP_RAM_BLOCK = 0x1800
  40. ESP_FLASH_BLOCK = 0x400
  41. # Default baudrate. The ROM auto-bauds, so we can use more or less whatever we want.
  42. ESP_ROM_BAUD = 115200
  43. # First byte of the application image
  44. ESP_IMAGE_MAGIC = 0xe9
  45. # Initial state for the checksum routine
  46. ESP_CHECKSUM_MAGIC = 0xef
  47. # OTP ROM addresses
  48. ESP_OTP_MAC0 = 0x3ff00050
  49. ESP_OTP_MAC1 = 0x3ff00054
  50. # Sflash stub: an assembly routine to read from spi flash and send to host
  51. SFLASH_STUB = "\x80\x3c\x00\x40\x1c\x4b\x00\x40\x21\x11\x00\x40\x00\x80" \
  52. "\xfe\x3f\xc1\xfb\xff\xd1\xf8\xff\x2d\x0d\x31\xfd\xff\x41\xf7\xff\x4a" \
  53. "\xdd\x51\xf9\xff\xc0\x05\x00\x21\xf9\xff\x31\xf3\xff\x41\xf5\xff\xc0" \
  54. "\x04\x00\x0b\xcc\x56\xec\xfd\x06\xff\xff\x00\x00"
  55. def __init__(self, port = 0, baud = ESP_ROM_BAUD):
  56. self._port = serial.Serial(port, baud)
  57. """ Read bytes from the serial port while performing SLIP unescaping """
  58. def read(self, length = 1):
  59. b = ''
  60. while len(b) < length:
  61. c = self._port.read(1)
  62. if c == '\xdb':
  63. c = self._port.read(1)
  64. if c == '\xdc':
  65. b = b + '\xc0'
  66. elif c == '\xdd':
  67. b = b + '\xdb'
  68. else:
  69. raise Exception('Invalid SLIP escape')
  70. else:
  71. b = b + c
  72. return b
  73. """ Write bytes to the serial port while performing SLIP escaping """
  74. def write(self, packet):
  75. buf = '\xc0'+(packet.replace('\xdb','\xdb\xdd').replace('\xc0','\xdb\xdc'))+'\xc0'
  76. self._port.write(buf)
  77. """ Calculate checksum of a blob, as it is defined by the ROM """
  78. @staticmethod
  79. def checksum(data, state = ESP_CHECKSUM_MAGIC):
  80. for b in data:
  81. state ^= ord(b)
  82. return state
  83. """ Send a request and read the response """
  84. def command(self, op = None, data = None, chk = 0):
  85. if op:
  86. # Construct and send request
  87. pkt = struct.pack('<BBHI', 0x00, op, len(data), chk) + data
  88. self.write(pkt)
  89. # Read header of response and parse
  90. if self._port.read(1) != '\xc0':
  91. raise Exception('Invalid head of packet')
  92. hdr = self.read(8)
  93. (resp, op_ret, len_ret, val) = struct.unpack('<BBHI', hdr)
  94. if resp != 0x01 or (op and op_ret != op):
  95. raise Exception('Invalid response')
  96. # The variable-length body
  97. body = self.read(len_ret)
  98. # Terminating byte
  99. if self._port.read(1) != chr(0xc0):
  100. raise Exception('Invalid end of packet')
  101. return val, body
  102. """ Perform a connection test """
  103. def sync(self):
  104. self.command(ESPROM.ESP_SYNC, '\x07\x07\x12\x20'+32*'\x55')
  105. for i in xrange(7):
  106. self.command()
  107. """ Try connecting repeatedly until successful, or giving up """
  108. def connect(self):
  109. print 'Connecting...'
  110. # RTS = CH_PD (i.e reset)
  111. # DTR = GPIO0
  112. # self._port.setRTS(True)
  113. # self._port.setDTR(True)
  114. # self._port.setRTS(False)
  115. # time.sleep(0.1)
  116. # self._port.setDTR(False)
  117. # NodeMCU devkit
  118. self._port.setRTS(True)
  119. self._port.setDTR(True)
  120. time.sleep(0.1)
  121. self._port.setRTS(False)
  122. self._port.setDTR(False)
  123. time.sleep(0.1)
  124. self._port.setRTS(True)
  125. time.sleep(0.1)
  126. self._port.setDTR(True)
  127. self._port.setRTS(False)
  128. time.sleep(0.3)
  129. self._port.setDTR(True)
  130. self._port.timeout = 0.5
  131. for i in xrange(10):
  132. try:
  133. self._port.flushInput()
  134. self._port.flushOutput()
  135. self.sync()
  136. self._port.timeout = 5
  137. return
  138. except:
  139. time.sleep(0.1)
  140. raise Exception('Failed to connect')
  141. """ Read memory address in target """
  142. def read_reg(self, addr):
  143. res = self.command(ESPROM.ESP_READ_REG, struct.pack('<I', addr))
  144. if res[1] != "\0\0":
  145. raise Exception('Failed to read target memory')
  146. return res[0]
  147. """ Write to memory address in target """
  148. def write_reg(self, addr, value, mask, delay_us = 0):
  149. if self.command(ESPROM.ESP_WRITE_REG,
  150. struct.pack('<IIII', addr, value, mask, delay_us))[1] != "\0\0":
  151. raise Exception('Failed to write target memory')
  152. """ Start downloading an application image to RAM """
  153. def mem_begin(self, size, blocks, blocksize, offset):
  154. if self.command(ESPROM.ESP_MEM_BEGIN,
  155. struct.pack('<IIII', size, blocks, blocksize, offset))[1] != "\0\0":
  156. raise Exception('Failed to enter RAM download mode')
  157. """ Send a block of an image to RAM """
  158. def mem_block(self, data, seq):
  159. if self.command(ESPROM.ESP_MEM_DATA,
  160. struct.pack('<IIII', len(data), seq, 0, 0)+data, ESPROM.checksum(data))[1] != "\0\0":
  161. raise Exception('Failed to write to target RAM')
  162. """ Leave download mode and run the application """
  163. def mem_finish(self, entrypoint = 0):
  164. if self.command(ESPROM.ESP_MEM_END,
  165. struct.pack('<II', int(entrypoint == 0), entrypoint))[1] != "\0\0":
  166. raise Exception('Failed to leave RAM download mode')
  167. """ Start downloading to Flash (performs an erase) """
  168. def flash_begin(self, size, offset):
  169. old_tmo = self._port.timeout
  170. num_blocks = (size + ESPROM.ESP_FLASH_BLOCK - 1) / ESPROM.ESP_FLASH_BLOCK
  171. self._port.timeout = 10
  172. if self.command(ESPROM.ESP_FLASH_BEGIN,
  173. struct.pack('<IIII', size, num_blocks, ESPROM.ESP_FLASH_BLOCK, offset))[1] != "\0\0":
  174. raise Exception('Failed to enter Flash download mode')
  175. self._port.timeout = old_tmo
  176. """ Write block to flash """
  177. def flash_block(self, data, seq):
  178. if self.command(ESPROM.ESP_FLASH_DATA,
  179. struct.pack('<IIII', len(data), seq, 0, 0)+data, ESPROM.checksum(data))[1] != "\0\0":
  180. raise Exception('Failed to write to target Flash')
  181. """ Leave flash mode and run/reboot """
  182. def flash_finish(self, reboot = False):
  183. pkt = struct.pack('<I', int(not reboot))
  184. if self.command(ESPROM.ESP_FLASH_END, pkt)[1] != "\0\0":
  185. raise Exception('Failed to leave Flash mode')
  186. """ Run application code in flash """
  187. def run(self, reboot = False):
  188. # Fake flash begin immediately followed by flash end
  189. self.flash_begin(0, 0)
  190. self.flash_finish(reboot)
  191. """ Read MAC from OTP ROM """
  192. def read_mac(self):
  193. mac0 = esp.read_reg(esp.ESP_OTP_MAC0)
  194. mac1 = esp.read_reg(esp.ESP_OTP_MAC1)
  195. if ((mac1 >> 16) & 0xff) == 0:
  196. oui = (0x18, 0xfe, 0x34)
  197. elif ((mac1 >> 16) & 0xff) == 1:
  198. oui = (0xac, 0xd0, 0x74)
  199. else:
  200. raise Exception("Unknown OUI")
  201. return oui + ((mac1 >> 8) & 0xff, mac1 & 0xff, (mac0 >> 24) & 0xff)
  202. """ Read SPI flash manufacturer and device id """
  203. def flash_id(self):
  204. self.flash_begin(0, 0)
  205. self.write_reg(0x60000240, 0x0, 0xffffffff)
  206. self.write_reg(0x60000200, 0x10000000, 0xffffffff)
  207. flash_id = esp.read_reg(0x60000240)
  208. self.flash_finish(False)
  209. return flash_id
  210. """ Read SPI flash """
  211. def flash_read(self, offset, size, count = 1):
  212. # Create a custom stub
  213. stub = struct.pack('<III', offset, size, count) + self.SFLASH_STUB
  214. # Trick ROM to initialize SFlash
  215. self.flash_begin(0, 0)
  216. # Download stub
  217. self.mem_begin(len(stub), 1, len(stub), 0x40100000)
  218. self.mem_block(stub, 0)
  219. self.mem_finish(0x4010001c)
  220. # Fetch the data
  221. data = ''
  222. for _ in xrange(count):
  223. if self._port.read(1) != '\xc0':
  224. raise Exception('Invalid head of packet (sflash read)')
  225. data += self.read(size)
  226. if self._port.read(1) != chr(0xc0):
  227. raise Exception('Invalid end of packet (sflash read)')
  228. return data
  229. """ Perform a chip erase of SPI flash """
  230. def flash_erase(self):
  231. # Trick ROM to initialize SFlash
  232. self.flash_begin(0, 0)
  233. # This is hacky: we don't have a custom stub, instead we trick
  234. # the bootloader to jump to the SPIEraseChip() routine and then halt/crash
  235. # when it tries to boot an unconfigured system.
  236. self.mem_begin(0,0,0,0x40100000)
  237. self.mem_finish(0x40004984)
  238. # Yup - there's no good way to detect if we succeeded.
  239. # It it on the other hand unlikely to fail.
  240. class ESPFirmwareImage:
  241. def __init__(self, filename = None):
  242. self.segments = []
  243. self.entrypoint = 0
  244. self.flash_mode = 0
  245. self.flash_size_freq = 0
  246. if filename is not None:
  247. f = file(filename, 'rb')
  248. (magic, segments, self.flash_mode, self.flash_size_freq, self.entrypoint) = struct.unpack('<BBBBI', f.read(8))
  249. # some sanity check
  250. if magic != ESPROM.ESP_IMAGE_MAGIC or segments > 16:
  251. raise Exception('Invalid firmware image')
  252. for i in xrange(segments):
  253. (offset, size) = struct.unpack('<II', f.read(8))
  254. if offset > 0x40200000 or offset < 0x3ffe0000 or size > 65536:
  255. raise Exception('Suspicious segment %x,%d' % (offset, size))
  256. self.segments.append((offset, size, f.read(size)))
  257. # Skip the padding. The checksum is stored in the last byte so that the
  258. # file is a multiple of 16 bytes.
  259. align = 15-(f.tell() % 16)
  260. f.seek(align, 1)
  261. self.checksum = ord(f.read(1))
  262. def add_segment(self, addr, data):
  263. # Data should be aligned on word boundary
  264. l = len(data)
  265. if l % 4:
  266. data += b"\x00" * (4 - l % 4)
  267. self.segments.append((addr, len(data), data))
  268. def save(self, filename):
  269. f = file(filename, 'wb')
  270. f.write(struct.pack('<BBBBI', ESPROM.ESP_IMAGE_MAGIC, len(self.segments),
  271. self.flash_mode, self.flash_size_freq, self.entrypoint))
  272. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  273. for (offset, size, data) in self.segments:
  274. f.write(struct.pack('<II', offset, size))
  275. f.write(data)
  276. checksum = ESPROM.checksum(data, checksum)
  277. align = 15-(f.tell() % 16)
  278. f.seek(align, 1)
  279. f.write(struct.pack('B', checksum))
  280. class ELFFile:
  281. def __init__(self, name):
  282. self.name = name
  283. self.symbols = None
  284. def _fetch_symbols(self):
  285. if self.symbols is not None:
  286. return
  287. self.symbols = {}
  288. try:
  289. tool_nm = "xtensa-lx106-elf-nm"
  290. if os.getenv('XTENSA_CORE')=='lx106':
  291. tool_nm = "xt-nm"
  292. proc = subprocess.Popen([tool_nm, self.name], stdout=subprocess.PIPE)
  293. except OSError:
  294. print "Error calling "+tool_nm+", do you have Xtensa toolchain in PATH?"
  295. sys.exit(1)
  296. for l in proc.stdout:
  297. fields = l.strip().split()
  298. self.symbols[fields[2]] = int(fields[0], 16)
  299. def get_symbol_addr(self, sym):
  300. self._fetch_symbols()
  301. return self.symbols[sym]
  302. def get_entry_point(self):
  303. tool_readelf = "xtensa-lx106-elf-readelf"
  304. if os.getenv('XTENSA_CORE')=='lx106':
  305. tool_objcopy = "xt-readelf"
  306. try:
  307. proc = subprocess.Popen([tool_readelf, "-h", self.name], stdout=subprocess.PIPE)
  308. except OSError:
  309. print "Error calling "+tool_nm+", do you have Xtensa toolchain in PATH?"
  310. sys.exit(1)
  311. for l in proc.stdout:
  312. fields = l.strip().split()
  313. if fields[0] == "Entry":
  314. return int(fields[3], 0);
  315. def load_section(self, section):
  316. tool_objcopy = "xtensa-lx106-elf-objcopy"
  317. if os.getenv('XTENSA_CORE')=='lx106':
  318. tool_objcopy = "xt-objcopy"
  319. subprocess.check_call([tool_objcopy, "--only-section", section, "-Obinary", self.name, ".tmp.section"])
  320. f = open(".tmp.section", "rb")
  321. data = f.read()
  322. f.close()
  323. os.remove(".tmp.section")
  324. return data
  325. def arg_auto_int(x):
  326. return int(x, 0)
  327. if __name__ == '__main__':
  328. parser = argparse.ArgumentParser(description = 'ESP8266 ROM Bootloader Utility', prog = 'esptool')
  329. parser.add_argument(
  330. '--port', '-p',
  331. help = 'Serial port device',
  332. default = '/dev/ttyUSB0')
  333. parser.add_argument(
  334. '--baud', '-b',
  335. help = 'Serial port baud rate',
  336. type = arg_auto_int,
  337. default = ESPROM.ESP_ROM_BAUD)
  338. subparsers = parser.add_subparsers(
  339. dest = 'operation',
  340. help = 'Run esptool {command} -h for additional help')
  341. parser_load_ram = subparsers.add_parser(
  342. 'load_ram',
  343. help = 'Download an image to RAM and execute')
  344. parser_load_ram.add_argument('filename', help = 'Firmware image')
  345. parser_dump_mem = subparsers.add_parser(
  346. 'dump_mem',
  347. help = 'Dump arbitrary memory to disk')
  348. parser_dump_mem.add_argument('address', help = 'Base address', type = arg_auto_int)
  349. parser_dump_mem.add_argument('size', help = 'Size of region to dump', type = arg_auto_int)
  350. parser_dump_mem.add_argument('filename', help = 'Name of binary dump')
  351. parser_read_mem = subparsers.add_parser(
  352. 'read_mem',
  353. help = 'Read arbitrary memory location')
  354. parser_read_mem.add_argument('address', help = 'Address to read', type = arg_auto_int)
  355. parser_write_mem = subparsers.add_parser(
  356. 'write_mem',
  357. help = 'Read-modify-write to arbitrary memory location')
  358. parser_write_mem.add_argument('address', help = 'Address to write', type = arg_auto_int)
  359. parser_write_mem.add_argument('value', help = 'Value', type = arg_auto_int)
  360. parser_write_mem.add_argument('mask', help = 'Mask of bits to write', type = arg_auto_int)
  361. parser_write_flash = subparsers.add_parser(
  362. 'write_flash',
  363. help = 'Write a binary blob to flash')
  364. parser_write_flash.add_argument('addr_filename', nargs = '+', help = 'Address and binary file to write there, separated by space')
  365. parser_write_flash.add_argument('--flash_freq', '-ff', help = 'SPI Flash frequency',
  366. choices = ['40m', '26m', '20m', '80m'], default = '40m')
  367. parser_write_flash.add_argument('--flash_mode', '-fm', help = 'SPI Flash mode',
  368. choices = ['qio', 'qout', 'dio', 'dout'], default = 'qio')
  369. parser_write_flash.add_argument('--flash_size', '-fs', help = 'SPI Flash size in Mbit',
  370. choices = ['4m', '2m', '8m', '16m', '32m'], default = '4m')
  371. parser_run = subparsers.add_parser(
  372. 'run',
  373. help = 'Run application code in flash')
  374. parser_image_info = subparsers.add_parser(
  375. 'image_info',
  376. help = 'Dump headers from an application image')
  377. parser_image_info.add_argument('filename', help = 'Image file to parse')
  378. parser_make_image = subparsers.add_parser(
  379. 'make_image',
  380. help = 'Create an application image from binary files')
  381. parser_make_image.add_argument('output', help = 'Output image file')
  382. parser_make_image.add_argument('--segfile', '-f', action = 'append', help = 'Segment input file')
  383. parser_make_image.add_argument('--segaddr', '-a', action = 'append', help = 'Segment base address', type = arg_auto_int)
  384. parser_make_image.add_argument('--entrypoint', '-e', help = 'Address of entry point', type = arg_auto_int, default = 0)
  385. parser_elf2image = subparsers.add_parser(
  386. 'elf2image',
  387. help = 'Create an application image from ELF file')
  388. parser_elf2image.add_argument('input', help = 'Input ELF file')
  389. parser_elf2image.add_argument('--output', '-o', help = 'Output filename prefix', type = str)
  390. parser_elf2image.add_argument('--flash_freq', '-ff', help = 'SPI Flash frequency',
  391. choices = ['40m', '26m', '20m', '80m'], default = '40m')
  392. parser_elf2image.add_argument('--flash_mode', '-fm', help = 'SPI Flash mode',
  393. choices = ['qio', 'qout', 'dio', 'dout'], default = 'qio')
  394. parser_elf2image.add_argument('--flash_size', '-fs', help = 'SPI Flash size in Mbit',
  395. choices = ['4m', '2m', '8m', '16m', '32m'], default = '4m')
  396. parser_read_mac = subparsers.add_parser(
  397. 'read_mac',
  398. help = 'Read MAC address from OTP ROM')
  399. parser_flash_id = subparsers.add_parser(
  400. 'flash_id',
  401. help = 'Read SPI flash manufacturer and device ID')
  402. parser_read_flash = subparsers.add_parser(
  403. 'read_flash',
  404. help = 'Read SPI flash content')
  405. parser_read_flash.add_argument('address', help = 'Start address', type = arg_auto_int)
  406. parser_read_flash.add_argument('size', help = 'Size of region to dump', type = arg_auto_int)
  407. parser_read_flash.add_argument('filename', help = 'Name of binary dump')
  408. parser_erase_flash = subparsers.add_parser(
  409. 'erase_flash',
  410. help = 'Perform Chip Erase on SPI flash')
  411. args = parser.parse_args()
  412. # Create the ESPROM connection object, if needed
  413. esp = None
  414. if args.operation not in ('image_info','make_image','elf2image'):
  415. esp = ESPROM(args.port, args.baud)
  416. esp.connect()
  417. # Do the actual work. Should probably be split into separate functions.
  418. if args.operation == 'load_ram':
  419. image = ESPFirmwareImage(args.filename)
  420. print 'RAM boot...'
  421. for (offset, size, data) in image.segments:
  422. print 'Downloading %d bytes at %08x...' % (size, offset),
  423. sys.stdout.flush()
  424. esp.mem_begin(size, math.ceil(size / float(esp.ESP_RAM_BLOCK)), esp.ESP_RAM_BLOCK, offset)
  425. seq = 0
  426. while len(data) > 0:
  427. esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq)
  428. data = data[esp.ESP_RAM_BLOCK:]
  429. seq += 1
  430. print 'done!'
  431. print 'All segments done, executing at %08x' % image.entrypoint
  432. esp.mem_finish(image.entrypoint)
  433. elif args.operation == 'read_mem':
  434. print '0x%08x = 0x%08x' % (args.address, esp.read_reg(args.address))
  435. elif args.operation == 'write_mem':
  436. esp.write_reg(args.address, args.value, args.mask, 0)
  437. print 'Wrote %08x, mask %08x to %08x' % (args.value, args.mask, args.address)
  438. elif args.operation == 'dump_mem':
  439. f = file(args.filename, 'wb')
  440. for i in xrange(args.size/4):
  441. d = esp.read_reg(args.address+(i*4))
  442. f.write(struct.pack('<I', d))
  443. if f.tell() % 1024 == 0:
  444. print '\r%d bytes read... (%d %%)' % (f.tell(), f.tell()*100/args.size),
  445. sys.stdout.flush()
  446. print 'Done!'
  447. elif args.operation == 'write_flash':
  448. assert len(args.addr_filename) % 2 == 0
  449. flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  450. flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40}[args.flash_size]
  451. flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  452. flash_info = struct.pack('BB', flash_mode, flash_size_freq)
  453. while args.addr_filename:
  454. address = int(args.addr_filename[0], 0)
  455. filename = args.addr_filename[1]
  456. args.addr_filename = args.addr_filename[2:]
  457. image = file(filename, 'rb').read()
  458. print 'Erasing flash...'
  459. blocks = math.ceil(len(image)/float(esp.ESP_FLASH_BLOCK))
  460. esp.flash_begin(blocks*esp.ESP_FLASH_BLOCK, address)
  461. seq = 0
  462. while len(image) > 0:
  463. print '\rWriting at 0x%08x... (%d %%)' % (address + seq*esp.ESP_FLASH_BLOCK, 100*(seq+1)/blocks),
  464. sys.stdout.flush()
  465. block = image[0:esp.ESP_FLASH_BLOCK]
  466. # Fix sflash config data
  467. if address == 0 and seq == 0 and block[0] == '\xe9':
  468. block = block[0:2] + flash_info + block[4:]
  469. # Pad the last block
  470. block = block + '\xff' * (esp.ESP_FLASH_BLOCK-len(block))
  471. esp.flash_block(block, seq)
  472. image = image[esp.ESP_FLASH_BLOCK:]
  473. seq += 1
  474. print
  475. print '\nLeaving...'
  476. esp.flash_finish(False)
  477. elif args.operation == 'run':
  478. esp.run()
  479. elif args.operation == 'image_info':
  480. image = ESPFirmwareImage(args.filename)
  481. print ('Entry point: %08x' % image.entrypoint) if image.entrypoint != 0 else 'Entry point not set'
  482. print '%d segments' % len(image.segments)
  483. print
  484. checksum = ESPROM.ESP_CHECKSUM_MAGIC
  485. for (idx, (offset, size, data)) in enumerate(image.segments):
  486. print 'Segment %d: %5d bytes at %08x' % (idx+1, size, offset)
  487. checksum = ESPROM.checksum(data, checksum)
  488. print
  489. print 'Checksum: %02x (%s)' % (image.checksum, 'valid' if image.checksum == checksum else 'invalid!')
  490. elif args.operation == 'make_image':
  491. image = ESPFirmwareImage()
  492. if len(args.segfile) == 0:
  493. raise Exception('No segments specified')
  494. if len(args.segfile) != len(args.segaddr):
  495. raise Exception('Number of specified files does not match number of specified addresses')
  496. for (seg, addr) in zip(args.segfile, args.segaddr):
  497. data = file(seg, 'rb').read()
  498. image.add_segment(addr, data)
  499. image.entrypoint = args.entrypoint
  500. image.save(args.output)
  501. elif args.operation == 'elf2image':
  502. if args.output is None:
  503. args.output = args.input + '-'
  504. e = ELFFile(args.input)
  505. image = ESPFirmwareImage()
  506. image.entrypoint = e.get_entry_point()
  507. for section, start in ((".text", "_text_start"), (".data", "_data_start"), (".rodata", "_rodata_start")):
  508. data = e.load_section(section)
  509. image.add_segment(e.get_symbol_addr(start), data)
  510. image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode]
  511. image.flash_size_freq = {'4m':0x00, '2m':0x10, '8m':0x20, '16m':0x30, '32m':0x40}[args.flash_size]
  512. image.flash_size_freq += {'40m':0, '26m':1, '20m':2, '80m': 0xf}[args.flash_freq]
  513. image.save(args.output + "0x00000.bin")
  514. data = e.load_section(".irom0.text")
  515. off = e.get_symbol_addr("_irom0_text_start") - 0x40200000
  516. assert off >= 0
  517. f = open(args.output + "0x%05x.bin" % off, "wb")
  518. f.write(data)
  519. f.close()
  520. elif args.operation == 'read_mac':
  521. mac = esp.read_mac()
  522. print 'MAC: %s' % ':'.join(map(lambda x: '%02x'%x, mac))
  523. elif args.operation == 'flash_id':
  524. flash_id = esp.flash_id()
  525. print 'Manufacturer: %02x' % (flash_id & 0xff)
  526. print 'Device: %02x%02x' % ((flash_id >> 8) & 0xff, (flash_id >> 16) & 0xff)
  527. elif args.operation == 'read_flash':
  528. print 'Please wait...'
  529. file(args.filename, 'wb').write(esp.flash_read(args.address, 1024, int(math.ceil(args.size / 1024.)))[:args.size])
  530. elif args.operation == 'erase_flash':
  531. esp.flash_erase()