IDFDUT.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. # SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. """ DUT for IDF applications """
  4. import collections
  5. import functools
  6. import io
  7. import os
  8. import os.path
  9. import re
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import time
  14. import pexpect
  15. import serial
  16. # python2 and python3 queue package name is different
  17. try:
  18. import Queue as _queue
  19. except ImportError:
  20. import queue as _queue # type: ignore
  21. from serial.tools import list_ports
  22. from tiny_test_fw import DUT, Utility
  23. try:
  24. import esptool
  25. except ImportError: # cheat and use IDF's copy of esptool if available
  26. idf_path = os.getenv('IDF_PATH')
  27. if not idf_path or not os.path.exists(idf_path):
  28. raise
  29. sys.path.insert(0, os.path.join(idf_path, 'components', 'esptool_py', 'esptool'))
  30. import esptool
  31. import espefuse
  32. import espsecure
  33. class IDFToolError(OSError):
  34. pass
  35. class IDFDUTException(RuntimeError):
  36. pass
  37. class IDFRecvThread(DUT.RecvThread):
  38. PERFORMANCE_PATTERN = re.compile(r'\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n')
  39. EXCEPTION_PATTERNS = [
  40. re.compile(r"(Guru Meditation Error: Core\s+\d panic'ed \([\w].*?\))"),
  41. re.compile(r'(abort\(\) was called at PC 0x[a-fA-F\d]{8} on core \d)'),
  42. re.compile(r'(rst 0x\d+ \(TG\dWDT_SYS_RESET|TGWDT_CPU_RESET\))')
  43. ]
  44. BACKTRACE_PATTERN = re.compile(r'Backtrace:((\s(0x[0-9a-f]{8}):0x[0-9a-f]{8})+)')
  45. BACKTRACE_ADDRESS_PATTERN = re.compile(r'(0x[0-9a-f]{8}):0x[0-9a-f]{8}')
  46. def __init__(self, read, dut):
  47. super(IDFRecvThread, self).__init__(read, dut)
  48. self.exceptions = _queue.Queue()
  49. self.performance_items = _queue.Queue()
  50. def collect_performance(self, comp_data):
  51. matches = self.PERFORMANCE_PATTERN.findall(comp_data)
  52. for match in matches:
  53. Utility.console_log('[Performance][{}]: {}'.format(match[0], match[1]), color='orange')
  54. self.performance_items.put((match[0], match[1]))
  55. def detect_exception(self, comp_data):
  56. for pattern in self.EXCEPTION_PATTERNS:
  57. start = 0
  58. while True:
  59. match = pattern.search(comp_data, pos=start)
  60. if match:
  61. start = match.end()
  62. self.exceptions.put(match.group(0))
  63. Utility.console_log('[Exception]: {}'.format(match.group(0)), color='red')
  64. else:
  65. break
  66. def detect_backtrace(self, comp_data):
  67. start = 0
  68. while True:
  69. match = self.BACKTRACE_PATTERN.search(comp_data, pos=start)
  70. if match:
  71. start = match.end()
  72. Utility.console_log('[Backtrace]:{}'.format(match.group(1)), color='red')
  73. # translate backtrace
  74. addresses = self.BACKTRACE_ADDRESS_PATTERN.findall(match.group(1))
  75. translated_backtrace = ''
  76. for addr in addresses:
  77. ret = self.dut.lookup_pc_address(addr)
  78. if ret:
  79. translated_backtrace += ret + '\n'
  80. if translated_backtrace:
  81. Utility.console_log('Translated backtrace\n:' + translated_backtrace, color='yellow')
  82. else:
  83. Utility.console_log('Failed to translate backtrace', color='yellow')
  84. else:
  85. break
  86. CHECK_FUNCTIONS = [collect_performance, detect_exception, detect_backtrace]
  87. def _uses_esptool(func):
  88. """ Suspend listener thread, connect with esptool,
  89. call target function with esptool instance,
  90. then resume listening for output
  91. """
  92. @functools.wraps(func)
  93. def handler(self, *args, **kwargs):
  94. self.stop_receive()
  95. settings = self.port_inst.get_settings()
  96. try:
  97. if not self.rom_inst:
  98. if not self.secure_boot_en:
  99. self.rom_inst = esptool.ESPLoader.detect_chip(self.port_inst)
  100. else:
  101. self.rom_inst = self.get_rom()(self.port_inst)
  102. self.rom_inst.connect('hard_reset')
  103. if (self.secure_boot_en):
  104. esp = self.rom_inst
  105. esp.flash_spi_attach(0)
  106. else:
  107. esp = self.rom_inst.run_stub()
  108. ret = func(self, esp, *args, **kwargs)
  109. # do hard reset after use esptool
  110. esp.hard_reset()
  111. finally:
  112. # always need to restore port settings
  113. self.port_inst.apply_settings(settings)
  114. self.start_receive()
  115. return ret
  116. return handler
  117. class IDFDUT(DUT.SerialDUT):
  118. """ IDF DUT, extends serial with esptool methods
  119. (Becomes aware of IDFApp instance which holds app-specific data)
  120. """
  121. # /dev/ttyAMA0 port is listed in Raspberry Pi
  122. # /dev/tty.Bluetooth-Incoming-Port port is listed in Mac
  123. INVALID_PORT_PATTERN = re.compile(r'AMA|Bluetooth')
  124. # if need to erase NVS partition in start app
  125. ERASE_NVS = True
  126. RECV_THREAD_CLS = IDFRecvThread
  127. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  128. super(IDFDUT, self).__init__(name, port, log_file, app, **kwargs)
  129. self.allow_dut_exception = allow_dut_exception
  130. self.exceptions = _queue.Queue()
  131. self.performance_items = _queue.Queue()
  132. self.rom_inst = None
  133. self.secure_boot_en = self.app.get_sdkconfig_config_value('CONFIG_SECURE_BOOT') and \
  134. not self.app.get_sdkconfig_config_value('CONFIG_EFUSE_VIRTUAL')
  135. @classmethod
  136. def get_rom(cls):
  137. raise NotImplementedError('This is an abstraction class, method not defined.')
  138. @classmethod
  139. def get_mac(cls, app, port):
  140. """
  141. get MAC address via esptool
  142. :param app: application instance (to get tool)
  143. :param port: serial port as string
  144. :return: MAC address or None
  145. """
  146. esp = None
  147. try:
  148. esp = cls.get_rom()(port)
  149. esp.connect()
  150. return esp.read_mac()
  151. except RuntimeError:
  152. return None
  153. finally:
  154. if esp:
  155. # do hard reset after use esptool
  156. esp.hard_reset()
  157. esp._port.close()
  158. @classmethod
  159. def confirm_dut(cls, port, **kwargs):
  160. inst = None
  161. try:
  162. expected_rom_class = cls.get_rom()
  163. except NotImplementedError:
  164. expected_rom_class = None
  165. try:
  166. # TODO: check whether 8266 works with this logic
  167. # Otherwise overwrite it in ESP8266DUT
  168. inst = esptool.ESPLoader.detect_chip(port)
  169. if expected_rom_class and type(inst) != expected_rom_class:
  170. raise RuntimeError('Target not expected')
  171. return inst.read_mac() is not None, get_target_by_rom_class(type(inst))
  172. except(esptool.FatalError, RuntimeError):
  173. return False, None
  174. finally:
  175. if inst is not None:
  176. inst._port.close()
  177. def _try_flash(self, erase_nvs):
  178. """
  179. Called by start_app()
  180. :return: None
  181. """
  182. flash_files = []
  183. encrypt_files = []
  184. try:
  185. # Open the files here to prevents us from having to seek back to 0
  186. # each time. Before opening them, we have to organize the lists the
  187. # way esptool.write_flash needs:
  188. # If encrypt is provided, flash_files contains all the files to
  189. # flash.
  190. # Else, flash_files contains the files to be flashed as plain text
  191. # and encrypt_files contains the ones to flash encrypted.
  192. flash_files = self.app.flash_files
  193. encrypt_files = self.app.encrypt_files
  194. encrypt = self.app.flash_settings.get('encrypt', False)
  195. if encrypt:
  196. flash_files = encrypt_files
  197. encrypt_files = []
  198. else:
  199. flash_files = [entry
  200. for entry in flash_files
  201. if entry not in encrypt_files]
  202. flash_files = [(offs, open(path, 'rb')) for (offs, path) in flash_files]
  203. encrypt_files = [(offs, open(path, 'rb')) for (offs, path) in encrypt_files]
  204. if erase_nvs:
  205. address = self.app.partition_table['nvs']['offset']
  206. size = self.app.partition_table['nvs']['size']
  207. nvs_file = tempfile.TemporaryFile()
  208. nvs_file.write(b'\xff' * size)
  209. nvs_file.seek(0)
  210. if not isinstance(address, int):
  211. address = int(address, 0)
  212. # We have to check whether this file needs to be added to
  213. # flash_files list or encrypt_files.
  214. # Get the CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT macro
  215. # value. If it is set to True, then NVS is always encrypted.
  216. sdkconfig_dict = self.app.get_sdkconfig()
  217. macro_encryption = 'CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT' in sdkconfig_dict
  218. # If the macro is not enabled (plain text flash) or all files
  219. # must be encrypted, add NVS to flash_files.
  220. if not macro_encryption or encrypt:
  221. flash_files.append((address, nvs_file))
  222. else:
  223. encrypt_files.append((address, nvs_file))
  224. self.write_flash_data(flash_files, encrypt_files, False, encrypt)
  225. finally:
  226. for (_, f) in flash_files:
  227. f.close()
  228. for (_, f) in encrypt_files:
  229. f.close()
  230. @_uses_esptool
  231. def write_flash_data(self, esp, flash_files=None, encrypt_files=None, ignore_flash_encryption_efuse_setting=True, encrypt=False):
  232. """
  233. Try flashing at a particular baud rate.
  234. Structured this way so @_uses_esptool will reconnect each time
  235. :return: None
  236. """
  237. last_error = None
  238. for baud_rate in [921600, 115200]:
  239. try:
  240. # fake flasher args object, this is a hack until
  241. # esptool Python API is improved
  242. class FlashArgs(object):
  243. def __init__(self, attributes):
  244. for key, value in attributes.items():
  245. self.__setattr__(key, value)
  246. # write_flash expects the parameter encrypt_files to be None and not
  247. # an empty list, so perform the check here
  248. flash_args = FlashArgs({
  249. 'flash_size': self.app.flash_settings['flash_size'],
  250. 'flash_mode': self.app.flash_settings['flash_mode'],
  251. 'flash_freq': self.app.flash_settings['flash_freq'],
  252. 'addr_filename': flash_files or None,
  253. 'encrypt_files': encrypt_files or None,
  254. 'no_stub': self.secure_boot_en,
  255. 'compress': not self.secure_boot_en,
  256. 'verify': False,
  257. 'encrypt': encrypt,
  258. 'ignore_flash_encryption_efuse_setting': ignore_flash_encryption_efuse_setting,
  259. 'erase_all': False,
  260. 'after': 'no_reset',
  261. })
  262. esp.change_baud(baud_rate)
  263. esptool.detect_flash_size(esp, flash_args)
  264. esptool.write_flash(esp, flash_args)
  265. break
  266. except RuntimeError as e:
  267. last_error = e
  268. else:
  269. raise last_error
  270. def image_info(self, path_to_file):
  271. """
  272. get hash256 of app
  273. :param: path: path to file
  274. :return: sha256 appended to app
  275. """
  276. old_stdout = sys.stdout
  277. new_stdout = io.StringIO()
  278. sys.stdout = new_stdout
  279. class Args(object):
  280. def __init__(self, attributes):
  281. for key, value in attributes.items():
  282. self.__setattr__(key, value)
  283. args = Args({
  284. 'chip': self.TARGET,
  285. 'filename': path_to_file,
  286. })
  287. esptool.image_info(args)
  288. output = new_stdout.getvalue()
  289. sys.stdout = old_stdout
  290. return output
  291. def start_app(self, erase_nvs=ERASE_NVS):
  292. """
  293. download and start app.
  294. :param: erase_nvs: whether erase NVS partition during flash
  295. :return: None
  296. """
  297. self._try_flash(erase_nvs)
  298. def start_app_no_enc(self):
  299. """
  300. download and start app.
  301. :param: erase_nvs: whether erase NVS partition during flash
  302. :return: None
  303. """
  304. flash_files = self.app.flash_files + self.app.encrypt_files
  305. self.write_flash(flash_files)
  306. def write_flash(self, flash_files=None, encrypt_files=None, ignore_flash_encryption_efuse_setting=True, encrypt=False):
  307. """
  308. Flash files
  309. :return: None
  310. """
  311. flash_offs_files = []
  312. encrypt_offs_files = []
  313. try:
  314. if flash_files:
  315. flash_offs_files = [(offs, open(path, 'rb')) for (offs, path) in flash_files]
  316. if encrypt_files:
  317. encrypt_offs_files = [(offs, open(path, 'rb')) for (offs, path) in encrypt_files]
  318. self.write_flash_data(flash_offs_files, encrypt_offs_files, ignore_flash_encryption_efuse_setting, encrypt)
  319. finally:
  320. for (_, f) in flash_offs_files:
  321. f.close()
  322. for (_, f) in encrypt_offs_files:
  323. f.close()
  324. def bootloader_flash(self):
  325. """
  326. download bootloader.
  327. :return: None
  328. """
  329. bootloader_path = os.path.join(self.app.binary_path, 'bootloader', 'bootloader.bin')
  330. offs = int(self.app.get_sdkconfig()['CONFIG_BOOTLOADER_OFFSET_IN_FLASH'], 0)
  331. flash_files = [(offs, bootloader_path)]
  332. self.write_flash(flash_files)
  333. @_uses_esptool
  334. def reset(self, esp):
  335. """
  336. hard reset DUT
  337. :return: None
  338. """
  339. # decorator `_use_esptool` will do reset
  340. # so we don't need to do anything in this method
  341. pass
  342. @_uses_esptool
  343. def erase_partition(self, esp, partition):
  344. """
  345. :param partition: partition name to erase
  346. :return: None
  347. """
  348. address = self.app.partition_table[partition]['offset']
  349. size = self.app.partition_table[partition]['size']
  350. esp.erase_region(address, size)
  351. @_uses_esptool
  352. def erase_flash(self, esp):
  353. """
  354. erase the flash completely
  355. :return: None
  356. """
  357. esp.erase_flash()
  358. @_uses_esptool
  359. def dump_flash(self, esp, output_file, **kwargs):
  360. """
  361. dump flash
  362. :param output_file: output file name, if relative path, will use sdk path as base path.
  363. :keyword partition: partition name, dump the partition.
  364. ``partition`` is preferred than using ``address`` and ``size``.
  365. :keyword address: dump from address (need to be used with size)
  366. :keyword size: dump size (need to be used with address)
  367. :return: None
  368. """
  369. if os.path.isabs(output_file) is False:
  370. output_file = os.path.relpath(output_file, self.app.get_log_folder())
  371. if 'partition' in kwargs:
  372. partition = self.app.partition_table[kwargs['partition']]
  373. _address = partition['offset']
  374. _size = partition['size']
  375. elif 'address' in kwargs and 'size' in kwargs:
  376. _address = kwargs['address']
  377. _size = kwargs['size']
  378. else:
  379. raise IDFToolError("You must specify 'partition' or ('address' and 'size') to dump flash")
  380. content = esp.read_flash(_address, _size)
  381. with open(output_file, 'wb') as f:
  382. f.write(content)
  383. @staticmethod
  384. def _sort_usb_ports(ports):
  385. """
  386. Move the usb ports to the very beginning
  387. :param ports: list of ports
  388. :return: list of ports with usb ports at beginning
  389. """
  390. usb_ports = []
  391. rest_ports = []
  392. for port in ports:
  393. if 'usb' in port.lower():
  394. usb_ports.append(port)
  395. else:
  396. rest_ports.append(port)
  397. return usb_ports + rest_ports
  398. @classmethod
  399. def list_available_ports(cls):
  400. # It will return other kinds of ports as well, such as ttyS* ports.
  401. # Give the usb ports higher priority
  402. ports = cls._sort_usb_ports([x.device for x in list_ports.comports()])
  403. espport = os.getenv('ESPPORT')
  404. if not espport:
  405. # It's a little hard filter out invalid port with `serial.tools.list_ports.grep()`:
  406. # The check condition in `grep` is: `if r.search(port) or r.search(desc) or r.search(hwid)`.
  407. # This means we need to make all 3 conditions fail, to filter out the port.
  408. # So some part of the filters will not be straight forward to users.
  409. # And negative regular expression (`^((?!aa|bb|cc).)*$`) is not easy to understand.
  410. # Filter out invalid port by our own will be much simpler.
  411. return [x for x in ports if not cls.INVALID_PORT_PATTERN.search(x)]
  412. # On MacOs with python3.6: type of espport is already utf8
  413. if isinstance(espport, type(u'')):
  414. port_hint = espport
  415. else:
  416. port_hint = espport.decode('utf8')
  417. # If $ESPPORT is a valid port, make it appear first in the list
  418. if port_hint in ports:
  419. ports.remove(port_hint)
  420. return [port_hint] + ports
  421. # On macOS, user may set ESPPORT to /dev/tty.xxx while
  422. # pySerial lists only the corresponding /dev/cu.xxx port
  423. if sys.platform == 'darwin' and 'tty.' in port_hint:
  424. port_hint = port_hint.replace('tty.', 'cu.')
  425. if port_hint in ports:
  426. ports.remove(port_hint)
  427. return [port_hint] + ports
  428. return ports
  429. def lookup_pc_address(self, pc_addr):
  430. cmd = ['%saddr2line' % self.TOOLCHAIN_PREFIX,
  431. '-pfiaC', '-e', self.app.elf_file, pc_addr]
  432. ret = ''
  433. try:
  434. translation = subprocess.check_output(cmd)
  435. ret = translation.decode()
  436. except OSError:
  437. pass
  438. return ret
  439. @staticmethod
  440. def _queue_read_all(source_queue):
  441. output = []
  442. while True:
  443. try:
  444. output.append(source_queue.get(timeout=0))
  445. except _queue.Empty:
  446. break
  447. return output
  448. def _queue_copy(self, source_queue, dest_queue):
  449. data = self._queue_read_all(source_queue)
  450. for d in data:
  451. dest_queue.put(d)
  452. def _get_from_queue(self, queue_name):
  453. self_queue = getattr(self, queue_name)
  454. if self.receive_thread:
  455. recv_thread_queue = getattr(self.receive_thread, queue_name)
  456. self._queue_copy(recv_thread_queue, self_queue)
  457. return self._queue_read_all(self_queue)
  458. def stop_receive(self):
  459. if self.receive_thread:
  460. for name in ['performance_items', 'exceptions']:
  461. source_queue = getattr(self.receive_thread, name)
  462. dest_queue = getattr(self, name)
  463. self._queue_copy(source_queue, dest_queue)
  464. super(IDFDUT, self).stop_receive()
  465. def get_exceptions(self):
  466. """ Get exceptions detected by DUT receive thread. """
  467. return self._get_from_queue('exceptions')
  468. def get_performance_items(self):
  469. """
  470. DUT receive thread will automatic collect performance results with pattern ``[Performance][name]: value\n``.
  471. This method is used to get all performance results.
  472. :return: a list of performance items.
  473. """
  474. return self._get_from_queue('performance_items')
  475. def close(self):
  476. super(IDFDUT, self).close()
  477. if not self.allow_dut_exception and self.get_exceptions():
  478. raise IDFDUTException('DUT exception detected on {}'.format(self))
  479. class ESP32DUT(IDFDUT):
  480. TARGET = 'esp32'
  481. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-'
  482. @classmethod
  483. def get_rom(cls):
  484. return esptool.ESP32ROM
  485. class ESP32S2DUT(IDFDUT):
  486. TARGET = 'esp32s2'
  487. TOOLCHAIN_PREFIX = 'xtensa-esp32s2-elf-'
  488. @classmethod
  489. def get_rom(cls):
  490. return esptool.ESP32S2ROM
  491. class ESP32S3DUT(IDFDUT):
  492. TARGET = 'esp32s3'
  493. TOOLCHAIN_PREFIX = 'xtensa-esp32s3-elf-'
  494. @classmethod
  495. def get_rom(cls):
  496. return esptool.ESP32S3ROM
  497. def erase_partition(self, esp, partition):
  498. raise NotImplementedError()
  499. class ESP32C3DUT(IDFDUT):
  500. TARGET = 'esp32c3'
  501. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  502. @classmethod
  503. def get_rom(cls):
  504. return esptool.ESP32C3ROM
  505. class ESP32C6DUT(IDFDUT):
  506. TARGET = 'esp32c6'
  507. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  508. @classmethod
  509. def get_rom(cls):
  510. return esptool.ESP32C6BETAROM
  511. class ESP32H2DUT(IDFDUT):
  512. TARGET = 'esp32h2'
  513. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  514. @classmethod
  515. def get_rom(cls):
  516. return esptool.ESP32H2ROM
  517. class ESP8266DUT(IDFDUT):
  518. TARGET = 'esp8266'
  519. TOOLCHAIN_PREFIX = 'xtensa-lx106-elf-'
  520. @classmethod
  521. def get_rom(cls):
  522. return esptool.ESP8266ROM
  523. def get_target_by_rom_class(cls):
  524. for c in [ESP32DUT, ESP32S2DUT, ESP32S3DUT, ESP32C3DUT, ESP32C6DUT, ESP32H2DUT, ESP8266DUT, IDFQEMUDUT]:
  525. if c.get_rom() == cls:
  526. return c.TARGET
  527. return None
  528. class IDFQEMUDUT(IDFDUT):
  529. TARGET = None
  530. TOOLCHAIN_PREFIX = None
  531. ERASE_NVS = True
  532. DEFAULT_EXPECT_TIMEOUT = 30 # longer timeout, since app startup takes more time in QEMU (due to slow SHA emulation)
  533. QEMU_SERIAL_PORT = 3334
  534. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  535. self.flash_image = tempfile.NamedTemporaryFile('rb+', suffix='.bin', prefix='qemu_flash_img')
  536. self.app = app
  537. self.flash_size = 4 * 1024 * 1024
  538. self._write_flash_img()
  539. args = [
  540. 'qemu-system-xtensa',
  541. '-nographic',
  542. '-machine', self.TARGET,
  543. '-drive', 'file={},if=mtd,format=raw'.format(self.flash_image.name),
  544. '-nic', 'user,model=open_eth',
  545. '-serial', 'tcp::{},server,nowait'.format(self.QEMU_SERIAL_PORT),
  546. '-S',
  547. '-global driver=timer.esp32.timg,property=wdt_disable,value=true']
  548. # TODO(IDF-1242): generate a temporary efuse binary, pass it to QEMU
  549. if 'QEMU_BIOS_PATH' in os.environ:
  550. args += ['-L', os.environ['QEMU_BIOS_PATH']]
  551. self.qemu = pexpect.spawn(' '.join(args), timeout=self.DEFAULT_EXPECT_TIMEOUT)
  552. self.qemu.expect_exact(b'(qemu)')
  553. super(IDFQEMUDUT, self).__init__(name, port, log_file, app, allow_dut_exception=allow_dut_exception, **kwargs)
  554. def _write_flash_img(self):
  555. self.flash_image.seek(0)
  556. self.flash_image.write(b'\x00' * self.flash_size)
  557. for offs, path in self.app.flash_files:
  558. with open(path, 'rb') as flash_file:
  559. contents = flash_file.read()
  560. self.flash_image.seek(offs)
  561. self.flash_image.write(contents)
  562. self.flash_image.flush()
  563. @classmethod
  564. def get_rom(cls):
  565. return esptool.ESP32ROM
  566. @classmethod
  567. def get_mac(cls, app, port):
  568. # TODO(IDF-1242): get this from QEMU/efuse binary
  569. return '11:22:33:44:55:66'
  570. @classmethod
  571. def confirm_dut(cls, port, **kwargs):
  572. return True, cls.TARGET
  573. def start_app(self, erase_nvs=ERASE_NVS):
  574. # TODO: implement erase_nvs
  575. # since the flash image is generated every time in the constructor, maybe this isn't needed...
  576. self.qemu.sendline(b'cont\n')
  577. self.qemu.expect_exact(b'(qemu)')
  578. def reset(self):
  579. self.qemu.sendline(b'system_reset\n')
  580. self.qemu.expect_exact(b'(qemu)')
  581. def erase_partition(self, partition):
  582. raise NotImplementedError('method erase_partition not implemented')
  583. def erase_flash(self):
  584. raise NotImplementedError('method erase_flash not implemented')
  585. def dump_flash(self, output_file, **kwargs):
  586. raise NotImplementedError('method dump_flash not implemented')
  587. @classmethod
  588. def list_available_ports(cls):
  589. return ['socket://localhost:{}'.format(cls.QEMU_SERIAL_PORT)]
  590. def close(self):
  591. super(IDFQEMUDUT, self).close()
  592. self.qemu.sendline(b'q\n')
  593. self.qemu.expect_exact(b'(qemu)')
  594. for _ in range(self.DEFAULT_EXPECT_TIMEOUT):
  595. if not self.qemu.isalive():
  596. break
  597. time.sleep(1)
  598. else:
  599. self.qemu.terminate(force=True)
  600. class ESP32QEMUDUT(IDFQEMUDUT):
  601. TARGET = 'esp32' # type: ignore
  602. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-' # type: ignore
  603. class IDFFPGADUT(IDFDUT):
  604. TARGET = None # type: str
  605. TOOLCHAIN_PREFIX = None # type: str
  606. ERASE_NVS = True
  607. FLASH_ENCRYPT_SCHEME = None # type: str
  608. FLASH_ENCRYPT_CNT_KEY = None # type: str
  609. FLASH_ENCRYPT_CNT_VAL = 0
  610. FLASH_ENCRYPT_PURPOSE = None # type: str
  611. SECURE_BOOT_EN_KEY = None # type: str
  612. SECURE_BOOT_EN_VAL = 0
  613. FLASH_SECTOR_SIZE = 4096
  614. def __init__(self, name, port, log_file, app, allow_dut_exception=False, efuse_reset_port=None, **kwargs):
  615. super(IDFFPGADUT, self).__init__(name, port, log_file, app, allow_dut_exception=allow_dut_exception, **kwargs)
  616. self.esp = self.get_rom()(port)
  617. self.efuses = None
  618. self.efuse_operations = None
  619. self.efuse_reset_port = efuse_reset_port
  620. @classmethod
  621. def get_rom(cls):
  622. raise NotImplementedError('This is an abstraction class, method not defined.')
  623. def erase_partition(self, esp, partition):
  624. raise NotImplementedError()
  625. def enable_efuses(self):
  626. # We use an extra COM port to reset the efuses on FPGA.
  627. # Connect DTR pin of the COM port to the efuse reset pin on daughter board
  628. # Set EFUSEPORT env variable to the extra COM port
  629. if not self.efuse_reset_port:
  630. raise RuntimeError('EFUSEPORT not specified')
  631. # Stop any previous serial port operation
  632. self.stop_receive()
  633. if self.secure_boot_en:
  634. self.esp.connect()
  635. self.efuses, self.efuse_operations = espefuse.get_efuses(self.esp, False, False, True)
  636. def burn_efuse(self, field, val):
  637. if not self.efuse_operations:
  638. self.enable_efuses()
  639. BurnEfuseArgs = collections.namedtuple('burn_efuse_args', ['name_value_pairs'])
  640. args = BurnEfuseArgs({field: val})
  641. self.efuse_operations.burn_efuse(self.esp, self.efuses, args)
  642. def burn_efuse_key(self, key, purpose, block):
  643. if not self.efuse_operations:
  644. self.enable_efuses()
  645. BurnKeyArgs = collections.namedtuple('burn_key_args',
  646. ['keyfile', 'keypurpose', 'block',
  647. 'force_write_always', 'no_write_protect', 'no_read_protect'])
  648. args = BurnKeyArgs([key],
  649. [purpose],
  650. [block],
  651. False, False, False)
  652. self.efuse_operations.burn_key(self.esp, self.efuses, args)
  653. def burn_efuse_key_digest(self, key, purpose, block):
  654. if not self.efuse_operations:
  655. self.enable_efuses()
  656. BurnDigestArgs = collections.namedtuple('burn_key_digest_args',
  657. ['keyfile', 'keypurpose', 'block',
  658. 'force_write_always', 'no_write_protect', 'no_read_protect'])
  659. args = BurnDigestArgs([open(key, 'rb')],
  660. [purpose],
  661. [block],
  662. False, False, True)
  663. self.efuse_operations.burn_key_digest(self.esp, self.efuses, args)
  664. def reset_efuses(self):
  665. if not self.efuse_reset_port:
  666. raise RuntimeError('EFUSEPORT not specified')
  667. with serial.Serial(self.efuse_reset_port) as efuseport:
  668. print('Resetting efuses')
  669. efuseport.dtr = 0
  670. self.port_inst.setRTS(1)
  671. self.port_inst.setRTS(0)
  672. time.sleep(1)
  673. efuseport.dtr = 1
  674. self.efuse_operations = None
  675. self.efuses = None
  676. def sign_data(self, data_file, key_files, version, append_signature=0):
  677. SignDataArgs = collections.namedtuple('sign_data_args',
  678. ['datafile','keyfile','output', 'version', 'append_signatures'])
  679. outfile = tempfile.NamedTemporaryFile()
  680. args = SignDataArgs(data_file, key_files, outfile.name, str(version), append_signature)
  681. espsecure.sign_data(args)
  682. outfile.seek(0)
  683. return outfile.read()
  684. class ESP32C3FPGADUT(IDFFPGADUT):
  685. TARGET = 'esp32c3'
  686. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  687. FLASH_ENCRYPT_SCHEME = 'AES-XTS'
  688. FLASH_ENCRYPT_CNT_KEY = 'SPI_BOOT_CRYPT_CNT'
  689. FLASH_ENCRYPT_CNT_VAL = 1
  690. FLASH_ENCRYPT_PURPOSE = 'XTS_AES_128_KEY'
  691. SECURE_BOOT_EN_KEY = 'SECURE_BOOT_EN'
  692. SECURE_BOOT_EN_VAL = 1
  693. @classmethod
  694. def get_rom(cls):
  695. return esptool.ESP32C3ROM
  696. def erase_partition(self, esp, partition):
  697. raise NotImplementedError()
  698. def flash_encrypt_burn_cnt(self):
  699. self.burn_efuse(self.FLASH_ENCRYPT_CNT_KEY, self.FLASH_ENCRYPT_CNT_VAL)
  700. def flash_encrypt_burn_key(self, key, block=0):
  701. self.burn_efuse_key(key, self.FLASH_ENCRYPT_PURPOSE, 'BLOCK_KEY%d' % block)
  702. def flash_encrypt_get_scheme(self):
  703. return self.FLASH_ENCRYPT_SCHEME
  704. def secure_boot_burn_en_bit(self):
  705. self.burn_efuse(self.SECURE_BOOT_EN_KEY, self.SECURE_BOOT_EN_VAL)
  706. def secure_boot_burn_digest(self, digest, key_index=0, block=0):
  707. self.burn_efuse_key_digest(digest, 'SECURE_BOOT_DIGEST%d' % key_index, 'BLOCK_KEY%d' % block)
  708. @classmethod
  709. def confirm_dut(cls, port, **kwargs):
  710. return True, cls.TARGET
  711. class ESP32S3FPGADUT(IDFFPGADUT):
  712. TARGET = 'esp32s3'
  713. TOOLCHAIN_PREFIX = 'xtensa-esp32s3-elf-'
  714. FLASH_ENCRYPT_SCHEME = 'AES-XTS'
  715. FLASH_ENCRYPT_CNT_KEY = 'SPI_BOOT_CRYPT_CNT'
  716. FLASH_ENCRYPT_CNT_VAL = 1
  717. FLASH_ENCRYPT_PURPOSE = 'XTS_AES_128_KEY'
  718. SECURE_BOOT_EN_KEY = 'SECURE_BOOT_EN'
  719. SECURE_BOOT_EN_VAL = 1
  720. @classmethod
  721. def get_rom(cls):
  722. return esptool.ESP32S3ROM
  723. def erase_partition(self, esp, partition):
  724. raise NotImplementedError()
  725. def flash_encrypt_burn_cnt(self):
  726. self.burn_efuse(self.FLASH_ENCRYPT_CNT_KEY, self.FLASH_ENCRYPT_CNT_VAL)
  727. def flash_encrypt_burn_key(self, key, block=0):
  728. self.burn_efuse_key(key, self.FLASH_ENCRYPT_PURPOSE, 'BLOCK_KEY%d' % block)
  729. def flash_encrypt_get_scheme(self):
  730. return self.FLASH_ENCRYPT_SCHEME
  731. def secure_boot_burn_en_bit(self):
  732. self.burn_efuse(self.SECURE_BOOT_EN_KEY, self.SECURE_BOOT_EN_VAL)
  733. def secure_boot_burn_digest(self, digest, key_index=0, block=0):
  734. self.burn_efuse_key_digest(digest, 'SECURE_BOOT_DIGEST%d' % key_index, 'BLOCK_KEY%d' % block)
  735. @classmethod
  736. def confirm_dut(cls, port, **kwargs):
  737. return True, cls.TARGET