panic_dut.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Unlicense OR CC0-1.0
  3. import logging
  4. import os
  5. import subprocess
  6. import sys
  7. from typing import Any, Dict, List, Optional, TextIO
  8. import pexpect
  9. from panic_utils import NoGdbProcessError, attach_logger, quote_string, sha256, verify_valid_gdb_subprocess
  10. from pygdbmi.gdbcontroller import GdbController
  11. from pytest_embedded_idf.app import IdfApp
  12. from pytest_embedded_idf.dut import IdfDut
  13. from pytest_embedded_idf.serial import IdfSerial
  14. class PanicTestDut(IdfDut):
  15. BOOT_CMD_ADDR = 0x9000
  16. BOOT_CMD_SIZE = 0x1000
  17. DEFAULT_EXPECT_TIMEOUT = 10
  18. COREDUMP_UART_START = '================= CORE DUMP START ================='
  19. COREDUMP_UART_END = '================= CORE DUMP END ================='
  20. app: IdfApp
  21. serial: IdfSerial
  22. def __init__(self, *args: Any, **kwargs: Any) -> None:
  23. super().__init__(*args, **kwargs)
  24. self.gdbmi: Optional[GdbController] = None
  25. # record this since pygdbmi is using logging.debug to generate some single character mess
  26. self.log_level = logging.getLogger().level
  27. # pygdbmi is using logging.debug to generate some single character mess
  28. if self.log_level <= logging.DEBUG:
  29. logging.getLogger().setLevel(logging.INFO)
  30. self.coredump_output: Optional[TextIO] = None
  31. def close(self) -> None:
  32. if self.gdbmi:
  33. logging.info('Waiting for GDB to exit')
  34. self.gdbmi.exit()
  35. super().close()
  36. def revert_log_level(self) -> None:
  37. logging.getLogger().setLevel(self.log_level)
  38. @property
  39. def is_xtensa(self) -> bool:
  40. return self.target in self.XTENSA_TARGETS
  41. def run_test_func(self, test_func_name: str) -> None:
  42. self.expect_exact('Enter test name:')
  43. self.write(test_func_name)
  44. self.expect_exact('Got test name: ' + test_func_name)
  45. def expect_none(self, pattern, **kwargs) -> None: # type: ignore
  46. """like dut.expect_all, but with an inverse logic"""
  47. if 'timeout' not in kwargs:
  48. kwargs['timeout'] = 1
  49. try:
  50. res = self.expect(pattern, **kwargs)
  51. raise AssertionError(f'Unexpected: {res.group().decode("utf8")}')
  52. except pexpect.TIMEOUT:
  53. pass
  54. def expect_backtrace(self) -> None:
  55. assert self.is_xtensa, 'Backtrace can be printed only on Xtensa'
  56. match = self.expect(r'Backtrace:( 0x[0-9a-fA-F]{8}:0x[0-9a-fA-F]{8})+(?P<corrupted> \|<-CORRUPTED)?')
  57. assert not match.group('corrupted')
  58. def expect_stack_dump(self) -> None:
  59. assert not self.is_xtensa, 'Stack memory dump is only printed on RISC-V'
  60. self.expect_exact('Stack memory:')
  61. def expect_gme(self, reason: str) -> None:
  62. """Expect method for Guru Meditation Errors"""
  63. self.expect_exact(f"Guru Meditation Error: Core 0 panic'ed ({reason})")
  64. def expect_reg_dump(self, core: int = 0) -> None:
  65. """Expect method for the register dump"""
  66. self.expect(r'Core\s+%d register dump:' % core)
  67. def expect_elf_sha256(self) -> None:
  68. """Expect method for ELF SHA256 line"""
  69. elf_sha256 = sha256(self.app.elf_file)
  70. elf_sha256_len = int(
  71. self.app.sdkconfig.get('CONFIG_APP_RETRIEVE_LEN_ELF_SHA', '16')
  72. )
  73. self.expect_exact('ELF file SHA256: ' + elf_sha256[0:elf_sha256_len])
  74. def _call_espcoredump(
  75. self, extra_args: List[str], coredump_file_name: str, output_file_name: str
  76. ) -> None:
  77. # no "with" here, since we need the file to be open for later inspection by the test case
  78. if not self.coredump_output:
  79. self.coredump_output = open(output_file_name, 'w')
  80. espcoredump_script = os.path.join(
  81. os.environ['IDF_PATH'], 'components', 'espcoredump', 'espcoredump.py'
  82. )
  83. espcoredump_args = [
  84. sys.executable,
  85. espcoredump_script,
  86. 'info_corefile',
  87. '--core',
  88. coredump_file_name,
  89. ]
  90. espcoredump_args += extra_args
  91. espcoredump_args.append(self.app.elf_file)
  92. logging.info('Running %s', ' '.join(espcoredump_args))
  93. logging.info('espcoredump output is written to %s', self.coredump_output.name)
  94. subprocess.check_call(espcoredump_args, stdout=self.coredump_output)
  95. self.coredump_output.flush()
  96. self.coredump_output.seek(0)
  97. def process_coredump_uart(self) -> None:
  98. """Extract the core dump from UART output of the test, run espcoredump on it"""
  99. self.expect(self.COREDUMP_UART_START)
  100. res = self.expect('(.+)' + self.COREDUMP_UART_END)
  101. coredump_base64 = res.group(1).decode('utf8')
  102. with open(os.path.join(self.logdir, 'coredump_data.b64'), 'w') as coredump_file:
  103. logging.info('Writing UART base64 core dump to %s', coredump_file.name)
  104. coredump_file.write(coredump_base64)
  105. output_file_name = os.path.join(self.logdir, 'coredump_uart_result.txt')
  106. self._call_espcoredump(
  107. ['--core-format', 'b64'], coredump_file.name, output_file_name
  108. )
  109. def process_coredump_flash(self) -> None:
  110. """Extract the core dump from flash, run espcoredump on it"""
  111. coredump_file_name = os.path.join(self.logdir, 'coredump_data.bin')
  112. logging.info('Writing flash binary core dump to %s', coredump_file_name)
  113. self.serial.dump_flash(partition='coredump', output=coredump_file_name)
  114. output_file_name = os.path.join(self.logdir, 'coredump_flash_result.txt')
  115. self._call_espcoredump(
  116. ['--core-format', 'raw'], coredump_file_name, output_file_name
  117. )
  118. def gdb_write(self, command: str) -> Any:
  119. """
  120. Wrapper to write to gdb with a longer timeout, as test runner
  121. host can be slow sometimes
  122. """
  123. assert self.gdbmi, 'This function should be called only after start_gdb'
  124. return self.gdbmi.write(command, timeout_sec=10)
  125. def start_gdb(self) -> None:
  126. """
  127. Runs GDB and connects it to the "serial" port of the DUT.
  128. After this, the DUT expect methods can no longer be used to capture output.
  129. """
  130. if self.is_xtensa:
  131. gdb_path = f'xtensa-{self.target}-elf-gdb'
  132. else:
  133. gdb_path = 'riscv32-esp-elf-gdb'
  134. try:
  135. from pygdbmi.constants import GdbTimeoutError
  136. default_gdb_args = ['--nx', '--quiet', '--interpreter=mi2']
  137. gdb_command = [gdb_path] + default_gdb_args
  138. self.gdbmi = GdbController(command=gdb_command)
  139. pygdbmi_logger = attach_logger()
  140. except ImportError:
  141. # fallback for pygdbmi<0.10.0.0.
  142. from pygdbmi.gdbcontroller import GdbTimeoutError
  143. self.gdbmi = GdbController(gdb_path=gdb_path)
  144. pygdbmi_logger = self.gdbmi.logger
  145. # pygdbmi logs to console by default, make it log to a file instead
  146. pygdbmi_log_file_name = os.path.join(self.logdir, 'pygdbmi_log.txt')
  147. pygdbmi_logger.setLevel(logging.DEBUG)
  148. while pygdbmi_logger.hasHandlers():
  149. pygdbmi_logger.removeHandler(pygdbmi_logger.handlers[0])
  150. log_handler = logging.FileHandler(pygdbmi_log_file_name)
  151. log_handler.setFormatter(
  152. logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
  153. )
  154. logging.info(f'Saving pygdbmi logs to {pygdbmi_log_file_name}')
  155. pygdbmi_logger.addHandler(log_handler)
  156. try:
  157. gdb_command = self.gdbmi.command
  158. except AttributeError:
  159. # fallback for pygdbmi < 0.10
  160. gdb_command = self.gdbmi.cmd
  161. logging.info(f'Running command: "{" ".join(quote_string(c) for c in gdb_command)}"')
  162. for _ in range(10):
  163. try:
  164. # GdbController creates a process with subprocess.Popen(). Is it really running? It is probable that
  165. # an RPI under high load will get non-responsive during creating a lot of processes.
  166. if not hasattr(self.gdbmi, 'verify_valid_gdb_subprocess'):
  167. # for pygdbmi >= 0.10.0.0
  168. verify_valid_gdb_subprocess(self.gdbmi.gdb_process)
  169. resp = self.gdbmi.get_gdb_response(
  170. timeout_sec=10
  171. ) # calls verify_valid_gdb_subprocess() internally for pygdbmi < 0.10.0.0
  172. # it will be interesting to look up this response if the next GDB command fails (times out)
  173. logging.info('GDB response: %s', resp)
  174. break # success
  175. except GdbTimeoutError:
  176. logging.warning(
  177. 'GDB internal error: cannot get response from the subprocess'
  178. )
  179. except NoGdbProcessError:
  180. logging.error('GDB internal error: process is not running')
  181. break # failure - TODO: create another GdbController
  182. except ValueError:
  183. logging.error(
  184. 'GDB internal error: select() returned an unexpected file number'
  185. )
  186. # Set up logging for GDB remote protocol
  187. gdb_remotelog_file_name = os.path.join(self.logdir, 'gdb_remote_log.txt')
  188. self.gdb_write('-gdb-set remotelogfile ' + gdb_remotelog_file_name)
  189. # Load the ELF file
  190. self.gdb_write('-file-exec-and-symbols {}'.format(self.app.elf_file))
  191. # Connect GDB to UART
  192. self.serial.close()
  193. logging.info('Connecting to GDB Stub...')
  194. self.gdb_write('-gdb-set serial baud 115200')
  195. if sys.platform == 'darwin':
  196. assert '/dev/tty.' not in self.serial.port, \
  197. '/dev/tty.* ports can\'t be used with GDB on macOS. Use with /dev/cu.* instead.'
  198. # Make sure we get the 'stopped' notification
  199. responses = self.gdb_write('-target-select remote ' + self.serial.port)
  200. stop_response = self.find_gdb_response('stopped', 'notify', responses)
  201. retries = 3
  202. while not stop_response and retries > 0:
  203. logging.info('Sending -exec-interrupt')
  204. responses = self.gdb_write('-exec-interrupt')
  205. stop_response = self.find_gdb_response('stopped', 'notify', responses)
  206. retries -= 1
  207. frame = stop_response['payload']['frame']
  208. if 'file' not in frame:
  209. frame['file'] = '?'
  210. if 'line' not in frame:
  211. frame['line'] = '?'
  212. logging.info('Stopped in {func} at {addr} ({file}:{line})'.format(**frame))
  213. # Drain remaining responses
  214. self.gdbmi.get_gdb_response(raise_error_on_timeout=False)
  215. def gdb_backtrace(self) -> Any:
  216. """
  217. Returns the list of stack frames for the current thread.
  218. Each frame is a dictionary, refer to pygdbmi docs for the format.
  219. """
  220. assert self.gdbmi
  221. responses = self.gdb_write('-stack-list-frames')
  222. return self.find_gdb_response('done', 'result', responses)['payload']['stack']
  223. @staticmethod
  224. def verify_gdb_backtrace(
  225. gdb_backtrace: List[Any], expected_functions_list: List[Any]
  226. ) -> None:
  227. """
  228. Raises an assert if the function names listed in expected_functions_list do not match the backtrace
  229. given by gdb_backtrace argument. The latter is in the same format as returned by gdb_backtrace()
  230. function.
  231. """
  232. actual_functions_list = [frame['func'] for frame in gdb_backtrace]
  233. if actual_functions_list != expected_functions_list:
  234. logging.error(f'Expected backtrace: {expected_functions_list}')
  235. logging.error(f'Actual backtrace: {actual_functions_list}')
  236. assert False, 'Got unexpected backtrace'
  237. @staticmethod
  238. def find_gdb_response(
  239. message: str, response_type: str, responses: List[Any]
  240. ) -> Any:
  241. """
  242. Helper function which extracts one response from an array of GDB responses, filtering
  243. by message and type. Returned message is a dictionary, refer to pygdbmi docs for the format.
  244. """
  245. def match_response(response: Dict[str, Any]) -> bool:
  246. return response['message'] == message and response['type'] == response_type # type: ignore
  247. filtered_responses = [r for r in responses if match_response(r)]
  248. if not filtered_responses:
  249. return None
  250. return filtered_responses[0]