u_boot_console_base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. # Copyright (c) 2015 Stephen Warren
  2. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # SPDX-License-Identifier: GPL-2.0
  5. # Common logic to interact with U-Boot via the console. This class provides
  6. # the interface that tests use to execute U-Boot shell commands and wait for
  7. # their results. Sub-classes exist to perform board-type-specific setup
  8. # operations, such as spawning a sub-process for Sandbox, or attaching to the
  9. # serial console of real hardware.
  10. import multiplexed_log
  11. import os
  12. import pytest
  13. import re
  14. import sys
  15. import u_boot_spawn
  16. # Regexes for text we expect U-Boot to send to the console.
  17. pattern_u_boot_spl_signon = re.compile('(U-Boot SPL \\d{4}\\.\\d{2}-[^\r\n]*)')
  18. pattern_u_boot_main_signon = re.compile('(U-Boot \\d{4}\\.\\d{2}-[^\r\n]*)')
  19. pattern_stop_autoboot_prompt = re.compile('Hit any key to stop autoboot: ')
  20. pattern_unknown_command = re.compile('Unknown command \'.*\' - try \'help\'')
  21. pattern_error_notification = re.compile('## Error: ')
  22. pattern_error_please_reset = re.compile('### ERROR ### Please RESET the board ###')
  23. PAT_ID = 0
  24. PAT_RE = 1
  25. bad_pattern_defs = (
  26. ('spl_signon', pattern_u_boot_spl_signon),
  27. ('main_signon', pattern_u_boot_main_signon),
  28. ('stop_autoboot_prompt', pattern_stop_autoboot_prompt),
  29. ('unknown_command', pattern_unknown_command),
  30. ('error_notification', pattern_error_notification),
  31. ('error_please_reset', pattern_error_please_reset),
  32. )
  33. class ConsoleDisableCheck(object):
  34. """Context manager (for Python's with statement) that temporarily disables
  35. the specified console output error check. This is useful when deliberately
  36. executing a command that is known to trigger one of the error checks, in
  37. order to test that the error condition is actually raised. This class is
  38. used internally by ConsoleBase::disable_check(); it is not intended for
  39. direct usage."""
  40. def __init__(self, console, check_type):
  41. self.console = console
  42. self.check_type = check_type
  43. def __enter__(self):
  44. self.console.disable_check_count[self.check_type] += 1
  45. self.console.eval_bad_patterns()
  46. def __exit__(self, extype, value, traceback):
  47. self.console.disable_check_count[self.check_type] -= 1
  48. self.console.eval_bad_patterns()
  49. class ConsoleBase(object):
  50. """The interface through which test functions interact with the U-Boot
  51. console. This primarily involves executing shell commands, capturing their
  52. results, and checking for common error conditions. Some common utilities
  53. are also provided too."""
  54. def __init__(self, log, config, max_fifo_fill):
  55. """Initialize a U-Boot console connection.
  56. Can only usefully be called by sub-classes.
  57. Args:
  58. log: A mulptiplex_log.Logfile object, to which the U-Boot output
  59. will be logged.
  60. config: A configuration data structure, as built by conftest.py.
  61. max_fifo_fill: The maximum number of characters to send to U-Boot
  62. command-line before waiting for U-Boot to echo the characters
  63. back. For UART-based HW without HW flow control, this value
  64. should be set less than the UART RX FIFO size to avoid
  65. overflow, assuming that U-Boot can't keep up with full-rate
  66. traffic at the baud rate.
  67. Returns:
  68. Nothing.
  69. """
  70. self.log = log
  71. self.config = config
  72. self.max_fifo_fill = max_fifo_fill
  73. self.logstream = self.log.get_stream('console', sys.stdout)
  74. # Array slice removes leading/trailing quotes
  75. self.prompt = self.config.buildconfig['config_sys_prompt'][1:-1]
  76. self.prompt_escaped = re.escape(self.prompt)
  77. self.p = None
  78. self.disable_check_count = {pat[PAT_ID]: 0 for pat in bad_pattern_defs}
  79. self.eval_bad_patterns()
  80. self.at_prompt = False
  81. self.at_prompt_logevt = None
  82. def eval_bad_patterns(self):
  83. self.bad_patterns = [pat[PAT_RE] for pat in bad_pattern_defs \
  84. if self.disable_check_count[pat[PAT_ID]] == 0]
  85. self.bad_pattern_ids = [pat[PAT_ID] for pat in bad_pattern_defs \
  86. if self.disable_check_count[pat[PAT_ID]] == 0]
  87. def close(self):
  88. """Terminate the connection to the U-Boot console.
  89. This function is only useful once all interaction with U-Boot is
  90. complete. Once this function is called, data cannot be sent to or
  91. received from U-Boot.
  92. Args:
  93. None.
  94. Returns:
  95. Nothing.
  96. """
  97. if self.p:
  98. self.p.close()
  99. self.logstream.close()
  100. def run_command(self, cmd, wait_for_echo=True, send_nl=True,
  101. wait_for_prompt=True):
  102. """Execute a command via the U-Boot console.
  103. The command is always sent to U-Boot.
  104. U-Boot echoes any command back to its output, and this function
  105. typically waits for that to occur. The wait can be disabled by setting
  106. wait_for_echo=False, which is useful e.g. when sending CTRL-C to
  107. interrupt a long-running command such as "ums".
  108. Command execution is typically triggered by sending a newline
  109. character. This can be disabled by setting send_nl=False, which is
  110. also useful when sending CTRL-C.
  111. This function typically waits for the command to finish executing, and
  112. returns the console output that it generated. This can be disabled by
  113. setting wait_for_prompt=False, which is useful when invoking a long-
  114. running command such as "ums".
  115. Args:
  116. cmd: The command to send.
  117. wait_for_each: Boolean indicating whether to wait for U-Boot to
  118. echo the command text back to its output.
  119. send_nl: Boolean indicating whether to send a newline character
  120. after the command string.
  121. wait_for_prompt: Boolean indicating whether to wait for the
  122. command prompt to be sent by U-Boot. This typically occurs
  123. immediately after the command has been executed.
  124. Returns:
  125. If wait_for_prompt == False:
  126. Nothing.
  127. Else:
  128. The output from U-Boot during command execution. In other
  129. words, the text U-Boot emitted between the point it echod the
  130. command string and emitted the subsequent command prompts.
  131. """
  132. if self.at_prompt and \
  133. self.at_prompt_logevt != self.logstream.logfile.cur_evt:
  134. self.logstream.write(self.prompt, implicit=True)
  135. try:
  136. self.at_prompt = False
  137. if send_nl:
  138. cmd += '\n'
  139. while cmd:
  140. # Limit max outstanding data, so UART FIFOs don't overflow
  141. chunk = cmd[:self.max_fifo_fill]
  142. cmd = cmd[self.max_fifo_fill:]
  143. self.p.send(chunk)
  144. if not wait_for_echo:
  145. continue
  146. chunk = re.escape(chunk)
  147. chunk = chunk.replace('\\\n', '[\r\n]')
  148. m = self.p.expect([chunk] + self.bad_patterns)
  149. if m != 0:
  150. self.at_prompt = False
  151. raise Exception('Bad pattern found on console: ' +
  152. self.bad_pattern_ids[m - 1])
  153. if not wait_for_prompt:
  154. return
  155. m = self.p.expect([self.prompt_escaped] + self.bad_patterns)
  156. if m != 0:
  157. self.at_prompt = False
  158. raise Exception('Bad pattern found on console: ' +
  159. self.bad_pattern_ids[m - 1])
  160. self.at_prompt = True
  161. self.at_prompt_logevt = self.logstream.logfile.cur_evt
  162. # Only strip \r\n; space/TAB might be significant if testing
  163. # indentation.
  164. return self.p.before.strip('\r\n')
  165. except Exception as ex:
  166. self.log.error(str(ex))
  167. self.cleanup_spawn()
  168. raise
  169. def ctrlc(self):
  170. """Send a CTRL-C character to U-Boot.
  171. This is useful in order to stop execution of long-running synchronous
  172. commands such as "ums".
  173. Args:
  174. None.
  175. Returns:
  176. Nothing.
  177. """
  178. self.log.action('Sending Ctrl-C')
  179. self.run_command(chr(3), wait_for_echo=False, send_nl=False)
  180. def wait_for(self, text):
  181. """Wait for a pattern to be emitted by U-Boot.
  182. This is useful when a long-running command such as "dfu" is executing,
  183. and it periodically emits some text that should show up at a specific
  184. location in the log file.
  185. Args:
  186. text: The text to wait for; either a string (containing raw text,
  187. not a regular expression) or an re object.
  188. Returns:
  189. Nothing.
  190. """
  191. if type(text) == type(''):
  192. text = re.escape(text)
  193. m = self.p.expect([text] + self.bad_patterns)
  194. if m != 0:
  195. raise Exception('Bad pattern found on console: ' +
  196. self.bad_pattern_ids[m - 1])
  197. def drain_console(self):
  198. """Read from and log the U-Boot console for a short time.
  199. U-Boot's console output is only logged when the test code actively
  200. waits for U-Boot to emit specific data. There are cases where tests
  201. can fail without doing this. For example, if a test asks U-Boot to
  202. enable USB device mode, then polls until a host-side device node
  203. exists. In such a case, it is useful to log U-Boot's console output
  204. in case U-Boot printed clues as to why the host-side even did not
  205. occur. This function will do that.
  206. Args:
  207. None.
  208. Returns:
  209. Nothing.
  210. """
  211. # If we are already not connected to U-Boot, there's nothing to drain.
  212. # This should only happen when a previous call to run_command() or
  213. # wait_for() failed (and hence the output has already been logged), or
  214. # the system is shutting down.
  215. if not self.p:
  216. return
  217. orig_timeout = self.p.timeout
  218. try:
  219. # Drain the log for a relatively short time.
  220. self.p.timeout = 1000
  221. # Wait for something U-Boot will likely never send. This will
  222. # cause the console output to be read and logged.
  223. self.p.expect(['This should never match U-Boot output'])
  224. except u_boot_spawn.Timeout:
  225. pass
  226. finally:
  227. self.p.timeout = orig_timeout
  228. def ensure_spawned(self):
  229. """Ensure a connection to a correctly running U-Boot instance.
  230. This may require spawning a new Sandbox process or resetting target
  231. hardware, as defined by the implementation sub-class.
  232. This is an internal function and should not be called directly.
  233. Args:
  234. None.
  235. Returns:
  236. Nothing.
  237. """
  238. if self.p:
  239. return
  240. try:
  241. self.at_prompt = False
  242. self.log.action('Starting U-Boot')
  243. self.p = self.get_spawn()
  244. # Real targets can take a long time to scroll large amounts of
  245. # text if LCD is enabled. This value may need tweaking in the
  246. # future, possibly per-test to be optimal. This works for 'help'
  247. # on board 'seaboard'.
  248. if not self.config.gdbserver:
  249. self.p.timeout = 30000
  250. self.p.logfile_read = self.logstream
  251. if self.config.buildconfig.get('CONFIG_SPL', False) == 'y':
  252. m = self.p.expect([pattern_u_boot_spl_signon] + self.bad_patterns)
  253. if m != 0:
  254. raise Exception('Bad pattern found on console: ' +
  255. self.bad_pattern_ids[m - 1])
  256. m = self.p.expect([pattern_u_boot_main_signon] + self.bad_patterns)
  257. if m != 0:
  258. raise Exception('Bad pattern found on console: ' +
  259. self.bad_pattern_ids[m - 1])
  260. signon = self.p.after
  261. build_idx = signon.find(', Build:')
  262. if build_idx == -1:
  263. self.u_boot_version_string = signon
  264. else:
  265. self.u_boot_version_string = signon[:build_idx]
  266. while True:
  267. m = self.p.expect([self.prompt_escaped,
  268. pattern_stop_autoboot_prompt] + self.bad_patterns)
  269. if m == 0:
  270. break
  271. if m == 1:
  272. self.p.send(chr(3)) # CTRL-C
  273. continue
  274. raise Exception('Bad pattern found on console: ' +
  275. self.bad_pattern_ids[m - 2])
  276. self.at_prompt = True
  277. self.at_prompt_logevt = self.logstream.logfile.cur_evt
  278. except Exception as ex:
  279. self.log.error(str(ex))
  280. self.cleanup_spawn()
  281. raise
  282. def cleanup_spawn(self):
  283. """Shut down all interaction with the U-Boot instance.
  284. This is used when an error is detected prior to re-establishing a
  285. connection with a fresh U-Boot instance.
  286. This is an internal function and should not be called directly.
  287. Args:
  288. None.
  289. Returns:
  290. Nothing.
  291. """
  292. try:
  293. if self.p:
  294. self.p.close()
  295. except:
  296. pass
  297. self.p = None
  298. def validate_version_string_in_text(self, text):
  299. """Assert that a command's output includes the U-Boot signon message.
  300. This is primarily useful for validating the "version" command without
  301. duplicating the signon text regex in a test function.
  302. Args:
  303. text: The command output text to check.
  304. Returns:
  305. Nothing. An exception is raised if the validation fails.
  306. """
  307. assert(self.u_boot_version_string in text)
  308. def disable_check(self, check_type):
  309. """Temporarily disable an error check of U-Boot's output.
  310. Create a new context manager (for use with the "with" statement) which
  311. temporarily disables a particular console output error check.
  312. Args:
  313. check_type: The type of error-check to disable. Valid values may
  314. be found in self.disable_check_count above.
  315. Returns:
  316. A context manager object.
  317. """
  318. return ConsoleDisableCheck(self, check_type)