u_boot_console_base.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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_escaped = re.escape(self.prompt)
  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_each: 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_escaped] + 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. def run_command_list(self, cmds):
  182. """Run a list of commands.
  183. This is a helper function to call run_command() with default arguments
  184. for each command in a list.
  185. Args:
  186. cmd: List of commands (each a string)
  187. Returns:
  188. Combined output of all commands, as a string
  189. """
  190. output = ''
  191. for cmd in cmds:
  192. output += self.run_command(cmd)
  193. return output
  194. def ctrlc(self):
  195. """Send a CTRL-C character to U-Boot.
  196. This is useful in order to stop execution of long-running synchronous
  197. commands such as "ums".
  198. Args:
  199. None.
  200. Returns:
  201. Nothing.
  202. """
  203. self.log.action('Sending Ctrl-C')
  204. self.run_command(chr(3), wait_for_echo=False, send_nl=False)
  205. def wait_for(self, text):
  206. """Wait for a pattern to be emitted by U-Boot.
  207. This is useful when a long-running command such as "dfu" is executing,
  208. and it periodically emits some text that should show up at a specific
  209. location in the log file.
  210. Args:
  211. text: The text to wait for; either a string (containing raw text,
  212. not a regular expression) or an re object.
  213. Returns:
  214. Nothing.
  215. """
  216. if type(text) == type(''):
  217. text = re.escape(text)
  218. m = self.p.expect([text] + self.bad_patterns)
  219. if m != 0:
  220. raise Exception('Bad pattern found on console: ' +
  221. self.bad_pattern_ids[m - 1])
  222. def drain_console(self):
  223. """Read from and log the U-Boot console for a short time.
  224. U-Boot's console output is only logged when the test code actively
  225. waits for U-Boot to emit specific data. There are cases where tests
  226. can fail without doing this. For example, if a test asks U-Boot to
  227. enable USB device mode, then polls until a host-side device node
  228. exists. In such a case, it is useful to log U-Boot's console output
  229. in case U-Boot printed clues as to why the host-side even did not
  230. occur. This function will do that.
  231. Args:
  232. None.
  233. Returns:
  234. Nothing.
  235. """
  236. # If we are already not connected to U-Boot, there's nothing to drain.
  237. # This should only happen when a previous call to run_command() or
  238. # wait_for() failed (and hence the output has already been logged), or
  239. # the system is shutting down.
  240. if not self.p:
  241. return
  242. orig_timeout = self.p.timeout
  243. try:
  244. # Drain the log for a relatively short time.
  245. self.p.timeout = 1000
  246. # Wait for something U-Boot will likely never send. This will
  247. # cause the console output to be read and logged.
  248. self.p.expect(['This should never match U-Boot output'])
  249. except u_boot_spawn.Timeout:
  250. pass
  251. finally:
  252. self.p.timeout = orig_timeout
  253. def ensure_spawned(self):
  254. """Ensure a connection to a correctly running U-Boot instance.
  255. This may require spawning a new Sandbox process or resetting target
  256. hardware, as defined by the implementation sub-class.
  257. This is an internal function and should not be called directly.
  258. Args:
  259. None.
  260. Returns:
  261. Nothing.
  262. """
  263. if self.p:
  264. return
  265. try:
  266. self.log.start_section('Starting U-Boot')
  267. self.at_prompt = False
  268. self.p = self.get_spawn()
  269. # Real targets can take a long time to scroll large amounts of
  270. # text if LCD is enabled. This value may need tweaking in the
  271. # future, possibly per-test to be optimal. This works for 'help'
  272. # on board 'seaboard'.
  273. if not self.config.gdbserver:
  274. self.p.timeout = 30000
  275. self.p.logfile_read = self.logstream
  276. bcfg = self.config.buildconfig
  277. config_spl = bcfg.get('config_spl', 'n') == 'y'
  278. config_spl_serial_support = bcfg.get('config_spl_serial_support',
  279. 'n') == 'y'
  280. env_spl_skipped = self.config.env.get('env__spl_skipped',
  281. False)
  282. if config_spl and config_spl_serial_support and not env_spl_skipped:
  283. m = self.p.expect([pattern_u_boot_spl_signon] +
  284. self.bad_patterns)
  285. if m != 0:
  286. raise Exception('Bad pattern found on SPL console: ' +
  287. self.bad_pattern_ids[m - 1])
  288. m = self.p.expect([pattern_u_boot_main_signon] + self.bad_patterns)
  289. if m != 0:
  290. raise Exception('Bad pattern found on console: ' +
  291. self.bad_pattern_ids[m - 1])
  292. self.u_boot_version_string = self.p.after
  293. while True:
  294. m = self.p.expect([self.prompt_escaped,
  295. pattern_stop_autoboot_prompt] + self.bad_patterns)
  296. if m == 0:
  297. break
  298. if m == 1:
  299. self.p.send(' ')
  300. continue
  301. raise Exception('Bad pattern found on console: ' +
  302. self.bad_pattern_ids[m - 2])
  303. self.at_prompt = True
  304. self.at_prompt_logevt = self.logstream.logfile.cur_evt
  305. except Exception as ex:
  306. self.log.error(str(ex))
  307. self.cleanup_spawn()
  308. raise
  309. finally:
  310. self.log.end_section('Starting U-Boot')
  311. def cleanup_spawn(self):
  312. """Shut down all interaction with the U-Boot instance.
  313. This is used when an error is detected prior to re-establishing a
  314. connection with a fresh U-Boot instance.
  315. This is an internal function and should not be called directly.
  316. Args:
  317. None.
  318. Returns:
  319. Nothing.
  320. """
  321. try:
  322. if self.p:
  323. self.p.close()
  324. except:
  325. pass
  326. self.p = None
  327. def get_spawn_output(self):
  328. """Return the start-up output from U-Boot
  329. Returns:
  330. The output produced by ensure_spawed(), as a string.
  331. """
  332. if self.p:
  333. return self.p.get_expect_output()
  334. return None
  335. def validate_version_string_in_text(self, text):
  336. """Assert that a command's output includes the U-Boot signon message.
  337. This is primarily useful for validating the "version" command without
  338. duplicating the signon text regex in a test function.
  339. Args:
  340. text: The command output text to check.
  341. Returns:
  342. Nothing. An exception is raised if the validation fails.
  343. """
  344. assert(self.u_boot_version_string in text)
  345. def disable_check(self, check_type):
  346. """Temporarily disable an error check of U-Boot's output.
  347. Create a new context manager (for use with the "with" statement) which
  348. temporarily disables a particular console output error check.
  349. Args:
  350. check_type: The type of error-check to disable. Valid values may
  351. be found in self.disable_check_count above.
  352. Returns:
  353. A context manager object.
  354. """
  355. return ConsoleDisableCheck(self, check_type)
  356. def temporary_timeout(self, timeout):
  357. """Temporarily set up different timeout for commands.
  358. Create a new context manager (for use with the "with" statement) which
  359. temporarily change timeout.
  360. Args:
  361. timeout: Time in milliseconds.
  362. Returns:
  363. A context manager object.
  364. """
  365. return ConsoleSetupTimeout(self, timeout)