serial_handler.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import hashlib
  4. import os
  5. import queue # noqa: F401
  6. import re
  7. import subprocess
  8. import time
  9. from typing import Callable, Optional
  10. import serial # noqa: F401
  11. from serial.tools import miniterm # noqa: F401
  12. from .chip_specific_config import get_chip_config
  13. from .console_parser import ConsoleParser, prompt_next_action # noqa: F401
  14. from .console_reader import ConsoleReader # noqa: F401
  15. from .constants import (CMD_APP_FLASH, CMD_ENTER_BOOT, CMD_MAKE, CMD_OUTPUT_TOGGLE, CMD_RESET, CMD_STOP,
  16. CMD_TOGGLE_LOGGING, CMD_TOGGLE_TIMESTAMPS, PANIC_DECODE_DISABLE, PANIC_END, PANIC_IDLE,
  17. PANIC_READING, PANIC_STACK_DUMP, PANIC_START)
  18. from .coredump import CoreDump
  19. from .exceptions import SerialStopException
  20. from .gdbhelper import GDBHelper
  21. from .line_matcher import LineMatcher
  22. from .logger import Logger
  23. from .output_helpers import yellow_print
  24. from .serial_reader import Reader
  25. def get_sha256(filename, block_size=65536): # type: (str, int) -> str
  26. sha256 = hashlib.sha256()
  27. with open(filename, 'rb') as f:
  28. for block in iter(lambda: f.read(block_size), b''):
  29. sha256.update(block)
  30. return sha256.hexdigest()
  31. def run_make(target, make, console, console_parser, event_queue, cmd_queue, logger):
  32. # type: (str, str, miniterm.Console, ConsoleParser, queue.Queue, queue.Queue, Logger) -> None
  33. if isinstance(make, list):
  34. popen_args = make + [target]
  35. else:
  36. popen_args = [make, target]
  37. yellow_print('Running %s...' % ' '.join(popen_args))
  38. p = subprocess.Popen(popen_args, env=os.environ)
  39. try:
  40. p.wait()
  41. except KeyboardInterrupt:
  42. p.wait()
  43. if p.returncode != 0:
  44. prompt_next_action('Build failed', console, console_parser, event_queue, cmd_queue)
  45. else:
  46. logger.output_enabled = True
  47. class SerialHandler:
  48. """
  49. The class is responsible for buffering serial input and performing corresponding commands.
  50. """
  51. def __init__(self, last_line_part, serial_check_exit, logger, decode_panic, reading_panic, panic_buffer, target,
  52. force_line_print, start_cmd_sent, serial_instance, encrypted, elf_file):
  53. # type: (bytes, bool, Logger, str, int, bytes,str, bool, bool, serial.Serial, bool, str) -> None
  54. self._last_line_part = last_line_part
  55. self._serial_check_exit = serial_check_exit
  56. self.logger = logger
  57. self._decode_panic = decode_panic
  58. self._reading_panic = reading_panic
  59. self._panic_buffer = panic_buffer
  60. self.target = target
  61. self._force_line_print = force_line_print
  62. self.start_cmd_sent = start_cmd_sent
  63. self.serial_instance = serial_instance
  64. self.encrypted = encrypted
  65. self.elf_file = elf_file
  66. def handle_serial_input(self, data, console_parser, coredump, gdb_helper, line_matcher,
  67. check_gdb_stub_and_run, finalize_line=False):
  68. # type: (bytes, ConsoleParser, CoreDump, Optional[GDBHelper], LineMatcher, Callable, bool) -> None
  69. # Remove "+" after Continue command
  70. if self.start_cmd_sent:
  71. self.start_cmd_sent = False
  72. pos = data.find(b'+')
  73. if pos != -1:
  74. data = data[(pos + 1):]
  75. sp = data.split(b'\n')
  76. if self._last_line_part != b'':
  77. # add unprocessed part from previous "data" to the first line
  78. sp[0] = self._last_line_part + sp[0]
  79. self._last_line_part = b''
  80. if sp[-1] != b'':
  81. # last part is not a full line
  82. self._last_line_part = sp.pop()
  83. for line in sp:
  84. if line == b'':
  85. continue
  86. if self._serial_check_exit and line == console_parser.exit_key.encode('latin-1'):
  87. raise SerialStopException()
  88. if gdb_helper:
  89. self.check_panic_decode_trigger(line, gdb_helper)
  90. with coredump.check(line):
  91. if self._force_line_print or line_matcher.match(line.decode(errors='ignore')):
  92. self.logger.print(line + b'\n')
  93. self.compare_elf_sha256(line.decode(errors='ignore'))
  94. self.logger.handle_possible_pc_address_in_line(line)
  95. check_gdb_stub_and_run(line)
  96. self._force_line_print = False
  97. # Now we have the last part (incomplete line) in _last_line_part. By
  98. # default we don't touch it and just wait for the arrival of the rest
  99. # of the line. But after some time when we didn't received it we need
  100. # to make a decision.
  101. force_print_or_matched = any((
  102. self._force_line_print,
  103. (finalize_line and line_matcher.match(self._last_line_part.decode(errors='ignore')))
  104. ))
  105. if self._last_line_part != b'' and force_print_or_matched:
  106. self._force_line_print = True
  107. self.logger.print(self._last_line_part)
  108. self.logger.handle_possible_pc_address_in_line(self._last_line_part)
  109. check_gdb_stub_and_run(self._last_line_part)
  110. # It is possible that the incomplete line cuts in half the PC
  111. # address. A small buffer is kept and will be used the next time
  112. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  113. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  114. # keep the last 9 characters.
  115. self.logger.pc_address_buffer = self._last_line_part[-9:]
  116. # GDB sequence can be cut in half also. GDB sequence is 7
  117. # characters long, therefore, we save the last 6 characters.
  118. if gdb_helper:
  119. gdb_helper.gdb_buffer = self._last_line_part[-6:]
  120. self._last_line_part = b''
  121. # else: keeping _last_line_part and it will be processed the next time
  122. # handle_serial_input is invoked
  123. def check_panic_decode_trigger(self, line, gdb_helper): # type: (bytes, GDBHelper) -> None
  124. if self._decode_panic == PANIC_DECODE_DISABLE:
  125. return
  126. if self._reading_panic == PANIC_IDLE and re.search(PANIC_START, line.decode('ascii', errors='ignore')):
  127. self._reading_panic = PANIC_READING
  128. yellow_print('Stack dump detected')
  129. if self._reading_panic == PANIC_READING and PANIC_STACK_DUMP in line:
  130. self.logger.output_enabled = False
  131. if self._reading_panic == PANIC_READING:
  132. self._panic_buffer += line.replace(b'\r', b'') + b'\n'
  133. if self._reading_panic == PANIC_READING and PANIC_END in line:
  134. self._reading_panic = PANIC_IDLE
  135. self.logger.output_enabled = True
  136. gdb_helper.process_panic_output(self._panic_buffer, self.logger, self.target)
  137. self._panic_buffer = b''
  138. def compare_elf_sha256(self, line): # type: (str) -> None
  139. elf_sha256_matcher = re.compile(
  140. r'ELF file SHA256:\s+(?P<sha256_flashed>[a-z0-9]+)'
  141. )
  142. file_sha256_flashed_match = re.search(elf_sha256_matcher, line)
  143. if not file_sha256_flashed_match:
  144. return
  145. file_sha256_flashed = file_sha256_flashed_match.group('sha256_flashed')
  146. if not os.path.exists(self.elf_file):
  147. yellow_print(f'ELF file not found. '
  148. f"You need to build & flash the project before running 'monitor', "
  149. f'and the binary on the device must match the one in the build directory exactly. ')
  150. else:
  151. file_sha256_build = get_sha256(self.elf_file)
  152. if file_sha256_flashed not in f'{file_sha256_build}':
  153. yellow_print(f'Warning: checksum mismatch between flashed and built applications. '
  154. f'Checksum of built application is {file_sha256_build}')
  155. def handle_commands(self, cmd, chip, run_make_func, console_reader, serial_reader):
  156. # type: (int, str, Callable, ConsoleReader, Reader) -> None
  157. config = get_chip_config(chip)
  158. reset_delay = config['reset']
  159. enter_boot_set = config['enter_boot_set']
  160. enter_boot_unset = config['enter_boot_unset']
  161. high = False
  162. low = True
  163. if chip == 'linux':
  164. if cmd in [CMD_RESET,
  165. CMD_MAKE,
  166. CMD_APP_FLASH,
  167. CMD_ENTER_BOOT]:
  168. yellow_print('linux target does not support this command')
  169. return
  170. if cmd == CMD_STOP:
  171. console_reader.stop()
  172. serial_reader.stop()
  173. elif cmd == CMD_RESET:
  174. self.serial_instance.setRTS(low)
  175. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  176. time.sleep(reset_delay)
  177. self.serial_instance.setRTS(high)
  178. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  179. self.logger.output_enabled = True
  180. elif cmd == CMD_MAKE:
  181. run_make_func('encrypted-flash' if self.encrypted else 'flash')
  182. elif cmd == CMD_APP_FLASH:
  183. run_make_func('encrypted-app-flash' if self.encrypted else 'app-flash')
  184. elif cmd == CMD_OUTPUT_TOGGLE:
  185. self.logger.output_toggle()
  186. elif cmd == CMD_TOGGLE_LOGGING:
  187. self.logger.toggle_logging()
  188. elif cmd == CMD_TOGGLE_TIMESTAMPS:
  189. self.logger.toggle_timestamps()
  190. elif cmd == CMD_ENTER_BOOT:
  191. yellow_print('Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart')
  192. self.serial_instance.setDTR(high) # IO0=HIGH
  193. self.serial_instance.setRTS(low) # EN=LOW, chip in reset
  194. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  195. time.sleep(enter_boot_set) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  196. self.serial_instance.setDTR(low) # IO0=LOW
  197. self.serial_instance.setRTS(high) # EN=HIGH, chip out of reset
  198. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  199. time.sleep(enter_boot_unset) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  200. self.serial_instance.setDTR(high) # IO0=HIGH, done
  201. else:
  202. raise RuntimeError('Bad command data %d' % cmd) # type: ignore
  203. class SerialHandlerNoElf(SerialHandler):
  204. # This method avoids using 'gdb_helper,' 'coredump' and 'handle_possible_pc_address_in_line'
  205. # where the elf file is required to be passed
  206. def handle_serial_input(self, data, console_parser, coredump, gdb_helper, line_matcher,
  207. check_gdb_stub_and_run, finalize_line=False):
  208. # type: (bytes, ConsoleParser, CoreDump, Optional[GDBHelper], LineMatcher, Callable, bool) -> None
  209. if self.start_cmd_sent:
  210. self.start_cmd_sent = False
  211. pos = data.find(b'+')
  212. if pos != -1:
  213. data = data[(pos + 1):]
  214. sp = data.split(b'\n')
  215. if self._last_line_part != b'':
  216. # add unprocessed part from previous "data" to the first line
  217. sp[0] = self._last_line_part + sp[0]
  218. self._last_line_part = b''
  219. if sp[-1] != b'':
  220. # last part is not a full line
  221. self._last_line_part = sp.pop()
  222. for line in sp:
  223. if line == b'':
  224. continue
  225. if self._serial_check_exit and line == console_parser.exit_key.encode('latin-1'):
  226. raise SerialStopException()
  227. self.logger.print(line + b'\n')
  228. self.compare_elf_sha256(line.decode(errors='ignore'))
  229. self._force_line_print = False
  230. force_print_or_matched = any((
  231. self._force_line_print,
  232. (finalize_line and line_matcher.match(self._last_line_part.decode(errors='ignore')))
  233. ))
  234. if self._last_line_part != b'' and force_print_or_matched:
  235. self._force_line_print = True
  236. self.logger.print(self._last_line_part)