IDFDUT.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ DUT for IDF applications """
  15. import functools
  16. import os
  17. import os.path
  18. import re
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import time
  23. import pexpect
  24. # python2 and python3 queue package name is different
  25. try:
  26. import Queue as _queue
  27. except ImportError:
  28. import queue as _queue
  29. from serial.tools import list_ports
  30. from tiny_test_fw import DUT, Utility
  31. from tiny_test_fw.Utility import format_case_id
  32. try:
  33. import esptool
  34. except ImportError: # cheat and use IDF's copy of esptool if available
  35. idf_path = os.getenv('IDF_PATH')
  36. if not idf_path or not os.path.exists(idf_path):
  37. raise
  38. sys.path.insert(0, os.path.join(idf_path, 'components', 'esptool_py', 'esptool'))
  39. import esptool
  40. class IDFToolError(OSError):
  41. pass
  42. class IDFDUTException(RuntimeError):
  43. pass
  44. class IDFRecvThread(DUT.RecvThread):
  45. PERFORMANCE_PATTERN = re.compile(r'\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n')
  46. EXCEPTION_PATTERNS = [
  47. re.compile(r"(Guru Meditation Error: Core\s+\d panic'ed \([\w].*?\))"),
  48. re.compile(r'(abort\(\) was called at PC 0x[a-fA-F\d]{8} on core \d)'),
  49. re.compile(r'(rst 0x\d+ \(TG\dWDT_SYS_RESET|TGWDT_CPU_RESET\))')
  50. ]
  51. BACKTRACE_PATTERN = re.compile(r'Backtrace:((\s(0x[0-9a-f]{8}):0x[0-9a-f]{8})+)')
  52. BACKTRACE_ADDRESS_PATTERN = re.compile(r'(0x[0-9a-f]{8}):0x[0-9a-f]{8}')
  53. def __init__(self, read, dut):
  54. super(IDFRecvThread, self).__init__(read, dut)
  55. self.exceptions = _queue.Queue()
  56. self.performance_items = _queue.Queue()
  57. def collect_performance(self, comp_data):
  58. matches = self.PERFORMANCE_PATTERN.findall(comp_data)
  59. for match in matches:
  60. Utility.console_log('[Performance][{}]: {}'.format(format_case_id(match[0], self.dut.app.target, self.dut.app.config_name), match[1]),
  61. color='orange')
  62. self.performance_items.put((match[0], match[1]))
  63. def detect_exception(self, comp_data):
  64. for pattern in self.EXCEPTION_PATTERNS:
  65. start = 0
  66. while True:
  67. match = pattern.search(comp_data, pos=start)
  68. if match:
  69. start = match.end()
  70. self.exceptions.put(match.group(0))
  71. Utility.console_log('[Exception]: {}'.format(match.group(0)), color='red')
  72. else:
  73. break
  74. def detect_backtrace(self, comp_data):
  75. start = 0
  76. while True:
  77. match = self.BACKTRACE_PATTERN.search(comp_data, pos=start)
  78. if match:
  79. start = match.end()
  80. Utility.console_log('[Backtrace]:{}'.format(match.group(1)), color='red')
  81. # translate backtrace
  82. addresses = self.BACKTRACE_ADDRESS_PATTERN.findall(match.group(1))
  83. translated_backtrace = ''
  84. for addr in addresses:
  85. ret = self.dut.lookup_pc_address(addr)
  86. if ret:
  87. translated_backtrace += ret + '\n'
  88. if translated_backtrace:
  89. Utility.console_log('Translated backtrace\n:' + translated_backtrace, color='yellow')
  90. else:
  91. Utility.console_log('Failed to translate backtrace', color='yellow')
  92. else:
  93. break
  94. CHECK_FUNCTIONS = [collect_performance, detect_exception, detect_backtrace]
  95. def _uses_esptool(func):
  96. """ Suspend listener thread, connect with esptool,
  97. call target function with esptool instance,
  98. then resume listening for output
  99. """
  100. @functools.wraps(func)
  101. def handler(self, *args, **kwargs):
  102. self.stop_receive()
  103. settings = self.port_inst.get_settings()
  104. try:
  105. if not self._rom_inst:
  106. self._rom_inst = esptool.ESPLoader.detect_chip(self.port_inst)
  107. self._rom_inst.connect('hard_reset')
  108. esp = self._rom_inst.run_stub()
  109. ret = func(self, esp, *args, **kwargs)
  110. # do hard reset after use esptool
  111. esp.hard_reset()
  112. finally:
  113. # always need to restore port settings
  114. self.port_inst.apply_settings(settings)
  115. self.start_receive()
  116. return ret
  117. return handler
  118. class IDFDUT(DUT.SerialDUT):
  119. """ IDF DUT, extends serial with esptool methods
  120. (Becomes aware of IDFApp instance which holds app-specific data)
  121. """
  122. # /dev/ttyAMA0 port is listed in Raspberry Pi
  123. # /dev/tty.Bluetooth-Incoming-Port port is listed in Mac
  124. INVALID_PORT_PATTERN = re.compile(r'AMA|Bluetooth')
  125. # if need to erase NVS partition in start app
  126. ERASE_NVS = True
  127. RECV_THREAD_CLS = IDFRecvThread
  128. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  129. super(IDFDUT, self).__init__(name, port, log_file, app, **kwargs)
  130. self.allow_dut_exception = allow_dut_exception
  131. self.exceptions = _queue.Queue()
  132. self.performance_items = _queue.Queue()
  133. self._rom_inst = None
  134. @classmethod
  135. def _get_rom(cls):
  136. raise NotImplementedError('This is an abstraction class, method not defined.')
  137. @classmethod
  138. def get_mac(cls, app, port):
  139. """
  140. get MAC address via esptool
  141. :param app: application instance (to get tool)
  142. :param port: serial port as string
  143. :return: MAC address or None
  144. """
  145. esp = None
  146. try:
  147. esp = cls._get_rom()(port)
  148. esp.connect()
  149. return esp.read_mac()
  150. except RuntimeError:
  151. return None
  152. finally:
  153. if esp:
  154. # do hard reset after use esptool
  155. esp.hard_reset()
  156. esp._port.close()
  157. @classmethod
  158. def confirm_dut(cls, port, **kwargs):
  159. inst = None
  160. try:
  161. expected_rom_class = cls._get_rom()
  162. except NotImplementedError:
  163. expected_rom_class = None
  164. try:
  165. # TODO: check whether 8266 works with this logic
  166. # Otherwise overwrite it in ESP8266DUT
  167. inst = esptool.ESPLoader.detect_chip(port)
  168. if expected_rom_class and type(inst) != expected_rom_class:
  169. raise RuntimeError('Target not expected')
  170. return inst.read_mac() is not None, get_target_by_rom_class(type(inst))
  171. except(esptool.FatalError, RuntimeError):
  172. return False, None
  173. finally:
  174. if inst is not None:
  175. inst._port.close()
  176. @_uses_esptool
  177. def _try_flash(self, esp, erase_nvs, baud_rate):
  178. """
  179. Called by start_app() to try flashing at a particular baud rate.
  180. Structured this way so @_uses_esptool will reconnect each time
  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. # fake flasher args object, this is a hack until
  225. # esptool Python API is improved
  226. class FlashArgs(object):
  227. def __init__(self, attributes):
  228. for key, value in attributes.items():
  229. self.__setattr__(key, value)
  230. # write_flash expects the parameter encrypt_files to be None and not
  231. # an empty list, so perform the check here
  232. flash_args = FlashArgs({
  233. 'flash_size': self.app.flash_settings['flash_size'],
  234. 'flash_mode': self.app.flash_settings['flash_mode'],
  235. 'flash_freq': self.app.flash_settings['flash_freq'],
  236. 'addr_filename': flash_files,
  237. 'encrypt_files': encrypt_files or None,
  238. 'no_stub': False,
  239. 'compress': True,
  240. 'verify': False,
  241. 'encrypt': encrypt,
  242. 'ignore_flash_encryption_efuse_setting': False,
  243. 'erase_all': False,
  244. })
  245. esp.change_baud(baud_rate)
  246. esptool.detect_flash_size(esp, flash_args)
  247. esptool.write_flash(esp, flash_args)
  248. finally:
  249. for (_, f) in flash_files:
  250. f.close()
  251. for (_, f) in encrypt_files:
  252. f.close()
  253. def start_app(self, erase_nvs=ERASE_NVS):
  254. """
  255. download and start app.
  256. :param: erase_nvs: whether erase NVS partition during flash
  257. :return: None
  258. """
  259. last_error = None
  260. for baud_rate in [921600, 115200]:
  261. try:
  262. self._try_flash(erase_nvs, baud_rate)
  263. break
  264. except RuntimeError as e:
  265. last_error = e
  266. else:
  267. raise last_error
  268. @_uses_esptool
  269. def reset(self, esp):
  270. """
  271. hard reset DUT
  272. :return: None
  273. """
  274. # decorator `_use_esptool` will do reset
  275. # so we don't need to do anything in this method
  276. pass
  277. @_uses_esptool
  278. def erase_partition(self, esp, partition):
  279. """
  280. :param partition: partition name to erase
  281. :return: None
  282. """
  283. raise NotImplementedError() # TODO: implement this
  284. # address = self.app.partition_table[partition]["offset"]
  285. size = self.app.partition_table[partition]['size']
  286. # TODO can use esp.erase_region() instead of this, I think
  287. with open('.erase_partition.tmp', 'wb') as f:
  288. f.write(chr(0xFF) * size)
  289. @_uses_esptool
  290. def erase_flash(self, esp):
  291. """
  292. erase the flash completely
  293. :return: None
  294. """
  295. esp.erase_flash()
  296. @_uses_esptool
  297. def dump_flash(self, esp, output_file, **kwargs):
  298. """
  299. dump flash
  300. :param output_file: output file name, if relative path, will use sdk path as base path.
  301. :keyword partition: partition name, dump the partition.
  302. ``partition`` is preferred than using ``address`` and ``size``.
  303. :keyword address: dump from address (need to be used with size)
  304. :keyword size: dump size (need to be used with address)
  305. :return: None
  306. """
  307. if os.path.isabs(output_file) is False:
  308. output_file = os.path.relpath(output_file, self.app.get_log_folder())
  309. if 'partition' in kwargs:
  310. partition = self.app.partition_table[kwargs['partition']]
  311. _address = partition['offset']
  312. _size = partition['size']
  313. elif 'address' in kwargs and 'size' in kwargs:
  314. _address = kwargs['address']
  315. _size = kwargs['size']
  316. else:
  317. raise IDFToolError("You must specify 'partition' or ('address' and 'size') to dump flash")
  318. content = esp.read_flash(_address, _size)
  319. with open(output_file, 'wb') as f:
  320. f.write(content)
  321. @staticmethod
  322. def _sort_usb_ports(ports):
  323. """
  324. Move the usb ports to the very beginning
  325. :param ports: list of ports
  326. :return: list of ports with usb ports at beginning
  327. """
  328. usb_ports = []
  329. rest_ports = []
  330. for port in ports:
  331. if 'usb' in port.lower():
  332. usb_ports.append(port)
  333. else:
  334. rest_ports.append(port)
  335. return usb_ports + rest_ports
  336. @classmethod
  337. def list_available_ports(cls):
  338. # It will return other kinds of ports as well, such as ttyS* ports.
  339. # Give the usb ports higher priority
  340. ports = cls._sort_usb_ports([x.device for x in list_ports.comports()])
  341. espport = os.getenv('ESPPORT')
  342. if not espport:
  343. # It's a little hard filter out invalid port with `serial.tools.list_ports.grep()`:
  344. # The check condition in `grep` is: `if r.search(port) or r.search(desc) or r.search(hwid)`.
  345. # This means we need to make all 3 conditions fail, to filter out the port.
  346. # So some part of the filters will not be straight forward to users.
  347. # And negative regular expression (`^((?!aa|bb|cc).)*$`) is not easy to understand.
  348. # Filter out invalid port by our own will be much simpler.
  349. return [x for x in ports if not cls.INVALID_PORT_PATTERN.search(x)]
  350. # On MacOs with python3.6: type of espport is already utf8
  351. if isinstance(espport, type(u'')):
  352. port_hint = espport
  353. else:
  354. port_hint = espport.decode('utf8')
  355. # If $ESPPORT is a valid port, make it appear first in the list
  356. if port_hint in ports:
  357. ports.remove(port_hint)
  358. return [port_hint] + ports
  359. # On macOS, user may set ESPPORT to /dev/tty.xxx while
  360. # pySerial lists only the corresponding /dev/cu.xxx port
  361. if sys.platform == 'darwin' and 'tty.' in port_hint:
  362. port_hint = port_hint.replace('tty.', 'cu.')
  363. if port_hint in ports:
  364. ports.remove(port_hint)
  365. return [port_hint] + ports
  366. return ports
  367. def lookup_pc_address(self, pc_addr):
  368. cmd = ['%saddr2line' % self.TOOLCHAIN_PREFIX,
  369. '-pfiaC', '-e', self.app.elf_file, pc_addr]
  370. ret = ''
  371. try:
  372. translation = subprocess.check_output(cmd)
  373. ret = translation.decode()
  374. except OSError:
  375. pass
  376. return ret
  377. @staticmethod
  378. def _queue_read_all(source_queue):
  379. output = []
  380. while True:
  381. try:
  382. output.append(source_queue.get(timeout=0))
  383. except _queue.Empty:
  384. break
  385. return output
  386. def _queue_copy(self, source_queue, dest_queue):
  387. data = self._queue_read_all(source_queue)
  388. for d in data:
  389. dest_queue.put(d)
  390. def _get_from_queue(self, queue_name):
  391. self_queue = getattr(self, queue_name)
  392. if self.receive_thread:
  393. recv_thread_queue = getattr(self.receive_thread, queue_name)
  394. self._queue_copy(recv_thread_queue, self_queue)
  395. return self._queue_read_all(self_queue)
  396. def stop_receive(self):
  397. if self.receive_thread:
  398. for name in ['performance_items', 'exceptions']:
  399. source_queue = getattr(self.receive_thread, name)
  400. dest_queue = getattr(self, name)
  401. self._queue_copy(source_queue, dest_queue)
  402. super(IDFDUT, self).stop_receive()
  403. def get_exceptions(self):
  404. """ Get exceptions detected by DUT receive thread. """
  405. return self._get_from_queue('exceptions')
  406. def get_performance_items(self):
  407. """
  408. DUT receive thread will automatic collect performance results with pattern ``[Performance][name]: value\n``.
  409. This method is used to get all performance results.
  410. :return: a list of performance items.
  411. """
  412. return self._get_from_queue('performance_items')
  413. def close(self):
  414. super(IDFDUT, self).close()
  415. if not self.allow_dut_exception and self.get_exceptions():
  416. Utility.console_log('DUT exception detected on {}'.format(self), color='red')
  417. raise IDFDUTException()
  418. class ESP32DUT(IDFDUT):
  419. TARGET = 'esp32'
  420. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-'
  421. @classmethod
  422. def _get_rom(cls):
  423. return esptool.ESP32ROM
  424. def erase_partition(self, esp, partition):
  425. raise NotImplementedError()
  426. class ESP32S2DUT(IDFDUT):
  427. TARGET = 'esp32s2'
  428. TOOLCHAIN_PREFIX = 'xtensa-esp32s2-elf-'
  429. @classmethod
  430. def _get_rom(cls):
  431. return esptool.ESP32S2ROM
  432. def erase_partition(self, esp, partition):
  433. raise NotImplementedError()
  434. class ESP32C3DUT(IDFDUT):
  435. TARGET = 'esp32c3'
  436. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  437. @classmethod
  438. def _get_rom(cls):
  439. return esptool.ESP32C3ROM
  440. def erase_partition(self, esp, partition):
  441. raise NotImplementedError()
  442. class ESP8266DUT(IDFDUT):
  443. TARGET = 'esp8266'
  444. TOOLCHAIN_PREFIX = 'xtensa-lx106-elf-'
  445. @classmethod
  446. def _get_rom(cls):
  447. return esptool.ESP8266ROM
  448. def erase_partition(self, esp, partition):
  449. raise NotImplementedError()
  450. def get_target_by_rom_class(cls):
  451. for c in [ESP32DUT, ESP32S2DUT, ESP32C3DUT, ESP8266DUT, IDFQEMUDUT]:
  452. if c._get_rom() == cls:
  453. return c.TARGET
  454. return None
  455. class IDFQEMUDUT(IDFDUT):
  456. TARGET = None
  457. TOOLCHAIN_PREFIX = None
  458. ERASE_NVS = True
  459. DEFAULT_EXPECT_TIMEOUT = 30 # longer timeout, since app startup takes more time in QEMU (due to slow SHA emulation)
  460. QEMU_SERIAL_PORT = 3334
  461. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  462. self.flash_image = tempfile.NamedTemporaryFile('rb+', suffix='.bin', prefix='qemu_flash_img')
  463. self.app = app
  464. self.flash_size = 4 * 1024 * 1024
  465. self._write_flash_img()
  466. args = [
  467. 'qemu-system-xtensa',
  468. '-nographic',
  469. '-machine', self.TARGET,
  470. '-drive', 'file={},if=mtd,format=raw'.format(self.flash_image.name),
  471. '-nic', 'user,model=open_eth',
  472. '-serial', 'tcp::{},server,nowait'.format(self.QEMU_SERIAL_PORT),
  473. '-S',
  474. '-global driver=timer.esp32.timg,property=wdt_disable,value=true']
  475. # TODO(IDF-1242): generate a temporary efuse binary, pass it to QEMU
  476. if 'QEMU_BIOS_PATH' in os.environ:
  477. args += ['-L', os.environ['QEMU_BIOS_PATH']]
  478. self.qemu = pexpect.spawn(' '.join(args), timeout=self.DEFAULT_EXPECT_TIMEOUT)
  479. self.qemu.expect_exact(b'(qemu)')
  480. super(IDFQEMUDUT, self).__init__(name, port, log_file, app, allow_dut_exception=allow_dut_exception, **kwargs)
  481. def _write_flash_img(self):
  482. self.flash_image.seek(0)
  483. self.flash_image.write(b'\x00' * self.flash_size)
  484. for offs, path in self.app.flash_files:
  485. with open(path, 'rb') as flash_file:
  486. contents = flash_file.read()
  487. self.flash_image.seek(offs)
  488. self.flash_image.write(contents)
  489. self.flash_image.flush()
  490. @classmethod
  491. def _get_rom(cls):
  492. return esptool.ESP32ROM
  493. @classmethod
  494. def get_mac(cls, app, port):
  495. # TODO(IDF-1242): get this from QEMU/efuse binary
  496. return '11:22:33:44:55:66'
  497. @classmethod
  498. def confirm_dut(cls, port, **kwargs):
  499. return True, cls.TARGET
  500. def start_app(self, erase_nvs=ERASE_NVS):
  501. # TODO: implement erase_nvs
  502. # since the flash image is generated every time in the constructor, maybe this isn't needed...
  503. self.qemu.sendline(b'cont\n')
  504. self.qemu.expect_exact(b'(qemu)')
  505. def reset(self):
  506. self.qemu.sendline(b'system_reset\n')
  507. self.qemu.expect_exact(b'(qemu)')
  508. def erase_partition(self, partition):
  509. raise NotImplementedError('method erase_partition not implemented')
  510. def erase_flash(self):
  511. raise NotImplementedError('method erase_flash not implemented')
  512. def dump_flash(self, output_file, **kwargs):
  513. raise NotImplementedError('method dump_flash not implemented')
  514. @classmethod
  515. def list_available_ports(cls):
  516. return ['socket://localhost:{}'.format(cls.QEMU_SERIAL_PORT)]
  517. def close(self):
  518. super(IDFQEMUDUT, self).close()
  519. self.qemu.sendline(b'q\n')
  520. self.qemu.expect_exact(b'(qemu)')
  521. for _ in range(self.DEFAULT_EXPECT_TIMEOUT):
  522. if not self.qemu.isalive():
  523. break
  524. time.sleep(1)
  525. else:
  526. self.qemu.terminate(force=True)
  527. class ESP32QEMUDUT(IDFQEMUDUT):
  528. TARGET = 'esp32'
  529. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-'