u_boot_console_base.py 17 KB

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