u_boot_console_base.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 ConsoleSetupTimeout(object):
  50. """Context manager (for Python's with statement) that temporarily sets up
  51. timeout for specific command. This is useful when execution time is greater
  52. then default 30s."""
  53. def __init__(self, console, timeout):
  54. self.p = console.p
  55. self.orig_timeout = self.p.timeout
  56. self.p.timeout = timeout
  57. def __enter__(self):
  58. return self
  59. def __exit__(self, extype, value, traceback):
  60. self.p.timeout = self.orig_timeout
  61. class ConsoleBase(object):
  62. """The interface through which test functions interact with the U-Boot
  63. console. This primarily involves executing shell commands, capturing their
  64. results, and checking for common error conditions. Some common utilities
  65. are also provided too."""
  66. def __init__(self, log, config, max_fifo_fill):
  67. """Initialize a U-Boot console connection.
  68. Can only usefully be called by sub-classes.
  69. Args:
  70. log: A mulptiplex_log.Logfile object, to which the U-Boot output
  71. will be logged.
  72. config: A configuration data structure, as built by conftest.py.
  73. max_fifo_fill: The maximum number of characters to send to U-Boot
  74. command-line before waiting for U-Boot to echo the characters
  75. back. For UART-based HW without HW flow control, this value
  76. should be set less than the UART RX FIFO size to avoid
  77. overflow, assuming that U-Boot can't keep up with full-rate
  78. traffic at the baud rate.
  79. Returns:
  80. Nothing.
  81. """
  82. self.log = log
  83. self.config = config
  84. self.max_fifo_fill = max_fifo_fill
  85. self.logstream = self.log.get_stream('console', sys.stdout)
  86. # Array slice removes leading/trailing quotes
  87. self.prompt = self.config.buildconfig['config_sys_prompt'][1:-1]
  88. self.prompt_compiled = re.compile('^' + re.escape(self.prompt), re.MULTILINE)
  89. self.p = None
  90. self.disable_check_count = {pat[PAT_ID]: 0 for pat in bad_pattern_defs}
  91. self.eval_bad_patterns()
  92. self.at_prompt = False
  93. self.at_prompt_logevt = None
  94. def eval_bad_patterns(self):
  95. self.bad_patterns = [pat[PAT_RE] for pat in bad_pattern_defs \
  96. if self.disable_check_count[pat[PAT_ID]] == 0]
  97. self.bad_pattern_ids = [pat[PAT_ID] for pat in bad_pattern_defs \
  98. if self.disable_check_count[pat[PAT_ID]] == 0]
  99. def close(self):
  100. """Terminate the connection to the U-Boot console.
  101. This function is only useful once all interaction with U-Boot is
  102. complete. Once this function is called, data cannot be sent to or
  103. received from U-Boot.
  104. Args:
  105. None.
  106. Returns:
  107. Nothing.
  108. """
  109. if self.p:
  110. self.p.close()
  111. self.logstream.close()
  112. def run_command(self, cmd, wait_for_echo=True, send_nl=True,
  113. wait_for_prompt=True):
  114. """Execute a command via the U-Boot console.
  115. The command is always sent to U-Boot.
  116. U-Boot echoes any command back to its output, and this function
  117. typically waits for that to occur. The wait can be disabled by setting
  118. wait_for_echo=False, which is useful e.g. when sending CTRL-C to
  119. interrupt a long-running command such as "ums".
  120. Command execution is typically triggered by sending a newline
  121. character. This can be disabled by setting send_nl=False, which is
  122. also useful when sending CTRL-C.
  123. This function typically waits for the command to finish executing, and
  124. returns the console output that it generated. This can be disabled by
  125. setting wait_for_prompt=False, which is useful when invoking a long-
  126. running command such as "ums".
  127. Args:
  128. cmd: The command to send.
  129. wait_for_echo: Boolean indicating whether to wait for U-Boot to
  130. echo the command text back to its output.
  131. send_nl: Boolean indicating whether to send a newline character
  132. after the command string.
  133. wait_for_prompt: Boolean indicating whether to wait for the
  134. command prompt to be sent by U-Boot. This typically occurs
  135. immediately after the command has been executed.
  136. Returns:
  137. If wait_for_prompt == False:
  138. Nothing.
  139. Else:
  140. The output from U-Boot during command execution. In other
  141. words, the text U-Boot emitted between the point it echod the
  142. command string and emitted the subsequent command prompts.
  143. """
  144. if self.at_prompt and \
  145. self.at_prompt_logevt != self.logstream.logfile.cur_evt:
  146. self.logstream.write(self.prompt, implicit=True)
  147. try:
  148. self.at_prompt = False
  149. if send_nl:
  150. cmd += '\n'
  151. while cmd:
  152. # Limit max outstanding data, so UART FIFOs don't overflow
  153. chunk = cmd[:self.max_fifo_fill]
  154. cmd = cmd[self.max_fifo_fill:]
  155. self.p.send(chunk)
  156. if not wait_for_echo:
  157. continue
  158. chunk = re.escape(chunk)
  159. chunk = chunk.replace('\\\n', '[\r\n]')
  160. m = self.p.expect([chunk] + self.bad_patterns)
  161. if m != 0:
  162. self.at_prompt = False
  163. raise Exception('Bad pattern found on console: ' +
  164. self.bad_pattern_ids[m - 1])
  165. if not wait_for_prompt:
  166. return
  167. m = self.p.expect([self.prompt_compiled] + self.bad_patterns)
  168. if m != 0:
  169. self.at_prompt = False
  170. raise Exception('Bad pattern found on console: ' +
  171. self.bad_pattern_ids[m - 1])
  172. self.at_prompt = True
  173. self.at_prompt_logevt = self.logstream.logfile.cur_evt
  174. # Only strip \r\n; space/TAB might be significant if testing
  175. # indentation.
  176. return self.p.before.strip('\r\n')
  177. except Exception as ex:
  178. self.log.error(str(ex))
  179. self.cleanup_spawn()
  180. raise
  181. finally:
  182. self.log.timestamp()
  183. def run_command_list(self, cmds):
  184. """Run a list of commands.
  185. This is a helper function to call run_command() with default arguments
  186. for each command in a list.
  187. Args:
  188. cmd: List of commands (each a string).
  189. Returns:
  190. A list of output strings from each command, one element for each
  191. command.
  192. """
  193. output = []
  194. for cmd in cmds:
  195. output.append(self.run_command(cmd))
  196. return output
  197. def ctrlc(self):
  198. """Send a CTRL-C character to U-Boot.
  199. This is useful in order to stop execution of long-running synchronous
  200. commands such as "ums".
  201. Args:
  202. None.
  203. Returns:
  204. Nothing.
  205. """
  206. self.log.action('Sending Ctrl-C')
  207. self.run_command(chr(3), wait_for_echo=False, send_nl=False)
  208. def wait_for(self, text):
  209. """Wait for a pattern to be emitted by U-Boot.
  210. This is useful when a long-running command such as "dfu" is executing,
  211. and it periodically emits some text that should show up at a specific
  212. location in the log file.
  213. Args:
  214. text: The text to wait for; either a string (containing raw text,
  215. not a regular expression) or an re object.
  216. Returns:
  217. Nothing.
  218. """
  219. if type(text) == type(''):
  220. text = re.escape(text)
  221. m = self.p.expect([text] + self.bad_patterns)
  222. if m != 0:
  223. raise Exception('Bad pattern found on console: ' +
  224. self.bad_pattern_ids[m - 1])
  225. def drain_console(self):
  226. """Read from and log the U-Boot console for a short time.
  227. U-Boot's console output is only logged when the test code actively
  228. waits for U-Boot to emit specific data. There are cases where tests
  229. can fail without doing this. For example, if a test asks U-Boot to
  230. enable USB device mode, then polls until a host-side device node
  231. exists. In such a case, it is useful to log U-Boot's console output
  232. in case U-Boot printed clues as to why the host-side even did not
  233. occur. This function will do that.
  234. Args:
  235. None.
  236. Returns:
  237. Nothing.
  238. """
  239. # If we are already not connected to U-Boot, there's nothing to drain.
  240. # This should only happen when a previous call to run_command() or
  241. # wait_for() failed (and hence the output has already been logged), or
  242. # the system is shutting down.
  243. if not self.p:
  244. return
  245. orig_timeout = self.p.timeout
  246. try:
  247. # Drain the log for a relatively short time.
  248. self.p.timeout = 1000
  249. # Wait for something U-Boot will likely never send. This will
  250. # cause the console output to be read and logged.
  251. self.p.expect(['This should never match U-Boot output'])
  252. except u_boot_spawn.Timeout:
  253. pass
  254. finally:
  255. self.p.timeout = orig_timeout
  256. def ensure_spawned(self):
  257. """Ensure a connection to a correctly running U-Boot instance.
  258. This may require spawning a new Sandbox process or resetting target
  259. hardware, as defined by the implementation sub-class.
  260. This is an internal function and should not be called directly.
  261. Args:
  262. None.
  263. Returns:
  264. Nothing.
  265. """
  266. if self.p:
  267. return
  268. try:
  269. self.log.start_section('Starting U-Boot')
  270. self.at_prompt = False
  271. self.p = self.get_spawn()
  272. # Real targets can take a long time to scroll large amounts of
  273. # text if LCD is enabled. This value may need tweaking in the
  274. # future, possibly per-test to be optimal. This works for 'help'
  275. # on board 'seaboard'.
  276. if not self.config.gdbserver:
  277. self.p.timeout = 30000
  278. self.p.logfile_read = self.logstream
  279. bcfg = self.config.buildconfig
  280. config_spl = bcfg.get('config_spl', 'n') == 'y'
  281. config_spl_serial_support = bcfg.get('config_spl_serial_support',
  282. 'n') == 'y'
  283. env_spl_skipped = self.config.env.get('env__spl_skipped',
  284. False)
  285. if config_spl and config_spl_serial_support and not env_spl_skipped:
  286. m = self.p.expect([pattern_u_boot_spl_signon] +
  287. self.bad_patterns)
  288. if m != 0:
  289. raise Exception('Bad pattern found on SPL console: ' +
  290. self.bad_pattern_ids[m - 1])
  291. m = self.p.expect([pattern_u_boot_main_signon] + self.bad_patterns)
  292. if m != 0:
  293. raise Exception('Bad pattern found on console: ' +
  294. self.bad_pattern_ids[m - 1])
  295. self.u_boot_version_string = self.p.after
  296. while True:
  297. m = self.p.expect([self.prompt_compiled,
  298. pattern_stop_autoboot_prompt] + self.bad_patterns)
  299. if m == 0:
  300. break
  301. if m == 1:
  302. self.p.send(' ')
  303. continue
  304. raise Exception('Bad pattern found on console: ' +
  305. self.bad_pattern_ids[m - 2])
  306. self.at_prompt = True
  307. self.at_prompt_logevt = self.logstream.logfile.cur_evt
  308. except Exception as ex:
  309. self.log.error(str(ex))
  310. self.cleanup_spawn()
  311. raise
  312. finally:
  313. self.log.timestamp()
  314. self.log.end_section('Starting U-Boot')
  315. def cleanup_spawn(self):
  316. """Shut down all interaction with the U-Boot instance.
  317. This is used when an error is detected prior to re-establishing a
  318. connection with a fresh U-Boot instance.
  319. This is an internal function and should not be called directly.
  320. Args:
  321. None.
  322. Returns:
  323. Nothing.
  324. """
  325. try:
  326. if self.p:
  327. self.p.close()
  328. except:
  329. pass
  330. self.p = None
  331. def restart_uboot(self):
  332. """Shut down and restart U-Boot."""
  333. self.cleanup_spawn()
  334. self.ensure_spawned()
  335. def get_spawn_output(self):
  336. """Return the start-up output from U-Boot
  337. Returns:
  338. The output produced by ensure_spawed(), as a string.
  339. """
  340. if self.p:
  341. return self.p.get_expect_output()
  342. return None
  343. def validate_version_string_in_text(self, text):
  344. """Assert that a command's output includes the U-Boot signon message.
  345. This is primarily useful for validating the "version" command without
  346. duplicating the signon text regex in a test function.
  347. Args:
  348. text: The command output text to check.
  349. Returns:
  350. Nothing. An exception is raised if the validation fails.
  351. """
  352. assert(self.u_boot_version_string in text)
  353. def disable_check(self, check_type):
  354. """Temporarily disable an error check of U-Boot's output.
  355. Create a new context manager (for use with the "with" statement) which
  356. temporarily disables a particular console output error check.
  357. Args:
  358. check_type: The type of error-check to disable. Valid values may
  359. be found in self.disable_check_count above.
  360. Returns:
  361. A context manager object.
  362. """
  363. return ConsoleDisableCheck(self, check_type)
  364. def temporary_timeout(self, timeout):
  365. """Temporarily set up different timeout for commands.
  366. Create a new context manager (for use with the "with" statement) which
  367. temporarily change timeout.
  368. Args:
  369. timeout: Time in milliseconds.
  370. Returns:
  371. A context manager object.
  372. """
  373. return ConsoleSetupTimeout(self, timeout)