u_boot_console_base.py 18 KB

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