u_boot_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # SPDX-License-Identifier: GPL-2.0
  2. # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
  3. """
  4. Utility code shared across multiple tests.
  5. """
  6. import hashlib
  7. import inspect
  8. import os
  9. import os.path
  10. import pathlib
  11. import signal
  12. import sys
  13. import time
  14. import re
  15. import pytest
  16. def md5sum_data(data):
  17. """Calculate the MD5 hash of some data.
  18. Args:
  19. data: The data to hash.
  20. Returns:
  21. The hash of the data, as a binary string.
  22. """
  23. h = hashlib.md5()
  24. h.update(data)
  25. return h.digest()
  26. def md5sum_file(fn, max_length=None):
  27. """Calculate the MD5 hash of the contents of a file.
  28. Args:
  29. fn: The filename of the file to hash.
  30. max_length: The number of bytes to hash. If the file has more
  31. bytes than this, they will be ignored. If None or omitted, the
  32. entire file will be hashed.
  33. Returns:
  34. The hash of the file content, as a binary string.
  35. """
  36. with open(fn, 'rb') as fh:
  37. if max_length:
  38. params = [max_length]
  39. else:
  40. params = []
  41. data = fh.read(*params)
  42. return md5sum_data(data)
  43. class PersistentRandomFile:
  44. """Generate and store information about a persistent file containing
  45. random data."""
  46. def __init__(self, u_boot_console, fn, size):
  47. """Create or process the persistent file.
  48. If the file does not exist, it is generated.
  49. If the file does exist, its content is hashed for later comparison.
  50. These files are always located in the "persistent data directory" of
  51. the current test run.
  52. Args:
  53. u_boot_console: A console connection to U-Boot.
  54. fn: The filename (without path) to create.
  55. size: The desired size of the file in bytes.
  56. Returns:
  57. Nothing.
  58. """
  59. self.fn = fn
  60. self.abs_fn = u_boot_console.config.persistent_data_dir + '/' + fn
  61. if os.path.exists(self.abs_fn):
  62. u_boot_console.log.action('Persistent data file ' + self.abs_fn +
  63. ' already exists')
  64. self.content_hash = md5sum_file(self.abs_fn)
  65. else:
  66. u_boot_console.log.action('Generating ' + self.abs_fn +
  67. ' (random, persistent, %d bytes)' % size)
  68. data = os.urandom(size)
  69. with open(self.abs_fn, 'wb') as fh:
  70. fh.write(data)
  71. self.content_hash = md5sum_data(data)
  72. def attempt_to_open_file(fn):
  73. """Attempt to open a file, without throwing exceptions.
  74. Any errors (exceptions) that occur during the attempt to open the file
  75. are ignored. This is useful in order to test whether a file (in
  76. particular, a device node) exists and can be successfully opened, in order
  77. to poll for e.g. USB enumeration completion.
  78. Args:
  79. fn: The filename to attempt to open.
  80. Returns:
  81. An open file handle to the file, or None if the file could not be
  82. opened.
  83. """
  84. try:
  85. return open(fn, 'rb')
  86. except:
  87. return None
  88. def wait_until_open_succeeds(fn):
  89. """Poll until a file can be opened, or a timeout occurs.
  90. Continually attempt to open a file, and return when this succeeds, or
  91. raise an exception after a timeout.
  92. Args:
  93. fn: The filename to attempt to open.
  94. Returns:
  95. An open file handle to the file.
  96. """
  97. for i in range(100):
  98. fh = attempt_to_open_file(fn)
  99. if fh:
  100. return fh
  101. time.sleep(0.1)
  102. raise Exception('File could not be opened')
  103. def wait_until_file_open_fails(fn, ignore_errors):
  104. """Poll until a file cannot be opened, or a timeout occurs.
  105. Continually attempt to open a file, and return when this fails, or
  106. raise an exception after a timeout.
  107. Args:
  108. fn: The filename to attempt to open.
  109. ignore_errors: Indicate whether to ignore timeout errors. If True, the
  110. function will simply return if a timeout occurs, otherwise an
  111. exception will be raised.
  112. Returns:
  113. Nothing.
  114. """
  115. for _ in range(100):
  116. fh = attempt_to_open_file(fn)
  117. if not fh:
  118. return
  119. fh.close()
  120. time.sleep(0.1)
  121. if ignore_errors:
  122. return
  123. raise Exception('File can still be opened')
  124. def run_and_log(u_boot_console, cmd, ignore_errors=False, stdin=None, env=None):
  125. """Run a command and log its output.
  126. Args:
  127. u_boot_console: A console connection to U-Boot.
  128. cmd: The command to run, as an array of argv[], or a string.
  129. If a string, note that it is split up so that quoted spaces
  130. will not be preserved. E.g. "fred and" becomes ['"fred', 'and"']
  131. ignore_errors: Indicate whether to ignore errors. If True, the function
  132. will simply return if the command cannot be executed or exits with
  133. an error code, otherwise an exception will be raised if such
  134. problems occur.
  135. stdin: Input string to pass to the command as stdin (or None)
  136. env: Environment to use, or None to use the current one
  137. Returns:
  138. The output as a string.
  139. """
  140. if isinstance(cmd, str):
  141. cmd = cmd.split()
  142. runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
  143. output = runner.run(cmd, ignore_errors=ignore_errors, stdin=stdin, env=env)
  144. runner.close()
  145. return output
  146. def run_and_log_expect_exception(u_boot_console, cmd, retcode, msg):
  147. """Run a command that is expected to fail.
  148. This runs a command and checks that it fails with the expected return code
  149. and exception method. If not, an exception is raised.
  150. Args:
  151. u_boot_console: A console connection to U-Boot.
  152. cmd: The command to run, as an array of argv[].
  153. retcode: Expected non-zero return code from the command.
  154. msg: String that should be contained within the command's output.
  155. """
  156. try:
  157. runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
  158. runner.run(cmd)
  159. except Exception:
  160. assert retcode == runner.exit_status
  161. assert msg in runner.output
  162. else:
  163. raise Exception("Expected an exception with retcode %d message '%s',"
  164. "but it was not raised" % (retcode, msg))
  165. finally:
  166. runner.close()
  167. ram_base = None
  168. def find_ram_base(u_boot_console):
  169. """Find the running U-Boot's RAM location.
  170. Probe the running U-Boot to determine the address of the first bank
  171. of RAM. This is useful for tests that test reading/writing RAM, or
  172. load/save files that aren't associated with some standard address
  173. typically represented in an environment variable such as
  174. ${kernel_addr_r}. The value is cached so that it only needs to be
  175. actively read once.
  176. Args:
  177. u_boot_console: A console connection to U-Boot.
  178. Returns:
  179. The address of U-Boot's first RAM bank, as an integer.
  180. """
  181. global ram_base
  182. if u_boot_console.config.buildconfig.get('config_cmd_bdi', 'n') != 'y':
  183. pytest.skip('bdinfo command not supported')
  184. if ram_base == -1:
  185. pytest.skip('Previously failed to find RAM bank start')
  186. if ram_base is not None:
  187. return ram_base
  188. with u_boot_console.log.section('find_ram_base'):
  189. response = u_boot_console.run_command('bdinfo')
  190. for l in response.split('\n'):
  191. if '-> start' in l or 'memstart =' in l:
  192. ram_base = int(l.split('=')[1].strip(), 16)
  193. break
  194. if ram_base is None:
  195. ram_base = -1
  196. raise Exception('Failed to find RAM bank start in `bdinfo`')
  197. # We don't want ram_base to be zero as some functions test if the given
  198. # address is NULL (0). Besides, on some RISC-V targets the low memory
  199. # is protected that prevents S-mode U-Boot from access.
  200. # Let's add 2MiB then (size of an ARM LPAE/v8 section).
  201. ram_base += 1024 * 1024 * 2
  202. return ram_base
  203. class PersistentFileHelperCtxMgr(object):
  204. """A context manager for Python's "with" statement, which ensures that any
  205. generated file is deleted (and hence regenerated) if its mtime is older
  206. than the mtime of the Python module which generated it, and gets an mtime
  207. newer than the mtime of the Python module which generated after it is
  208. generated. Objects of this type should be created by factory function
  209. persistent_file_helper rather than directly."""
  210. def __init__(self, log, filename):
  211. """Initialize a new object.
  212. Args:
  213. log: The Logfile object to log to.
  214. filename: The filename of the generated file.
  215. Returns:
  216. Nothing.
  217. """
  218. self.log = log
  219. self.filename = filename
  220. def __enter__(self):
  221. frame = inspect.stack()[1]
  222. module = inspect.getmodule(frame[0])
  223. self.module_filename = module.__file__
  224. self.module_timestamp = os.path.getmtime(self.module_filename)
  225. if os.path.exists(self.filename):
  226. filename_timestamp = os.path.getmtime(self.filename)
  227. if filename_timestamp < self.module_timestamp:
  228. self.log.action('Removing stale generated file ' +
  229. self.filename)
  230. pathlib.Path(self.filename).unlink()
  231. def __exit__(self, extype, value, traceback):
  232. if extype:
  233. try:
  234. pathlib.Path(self.filename).unlink()
  235. except Exception:
  236. pass
  237. return
  238. logged = False
  239. for _ in range(20):
  240. filename_timestamp = os.path.getmtime(self.filename)
  241. if filename_timestamp > self.module_timestamp:
  242. break
  243. if not logged:
  244. self.log.action(
  245. 'Waiting for generated file timestamp to increase')
  246. logged = True
  247. os.utime(self.filename)
  248. time.sleep(0.1)
  249. def persistent_file_helper(u_boot_log, filename):
  250. """Manage the timestamps and regeneration of a persistent generated
  251. file. This function creates a context manager for Python's "with"
  252. statement
  253. Usage:
  254. with persistent_file_helper(u_boot_console.log, filename):
  255. code to generate the file, if it's missing.
  256. Args:
  257. u_boot_log: u_boot_console.log.
  258. filename: The filename of the generated file.
  259. Returns:
  260. A context manager object.
  261. """
  262. return PersistentFileHelperCtxMgr(u_boot_log, filename)
  263. def crc32(u_boot_console, address, count):
  264. """Helper function used to compute the CRC32 value of a section of RAM.
  265. Args:
  266. u_boot_console: A U-Boot console connection.
  267. address: Address where data starts.
  268. count: Amount of data to use for calculation.
  269. Returns:
  270. CRC32 value
  271. """
  272. bcfg = u_boot_console.config.buildconfig
  273. has_cmd_crc32 = bcfg.get('config_cmd_crc32', 'n') == 'y'
  274. assert has_cmd_crc32, 'Cannot compute crc32 without CONFIG_CMD_CRC32.'
  275. output = u_boot_console.run_command('crc32 %08x %x' % (address, count))
  276. m = re.search('==> ([0-9a-fA-F]{8})$', output)
  277. assert m, 'CRC32 operation failed.'
  278. return m.group(1)
  279. def waitpid(pid, timeout=60, kill=False):
  280. """Wait a process to terminate by its PID
  281. This is an alternative to a os.waitpid(pid, 0) call that works on
  282. processes that aren't children of the python process.
  283. Args:
  284. pid: PID of a running process.
  285. timeout: Time in seconds to wait.
  286. kill: Whether to forcibly kill the process after timeout.
  287. Returns:
  288. True, if the process ended on its own.
  289. False, if the process was killed by this function.
  290. Raises:
  291. TimeoutError, if the process is still running after timeout.
  292. """
  293. try:
  294. for _ in range(timeout):
  295. os.kill(pid, 0)
  296. time.sleep(1)
  297. if kill:
  298. os.kill(pid, signal.SIGKILL)
  299. return False
  300. except ProcessLookupError:
  301. return True
  302. raise TimeoutError(
  303. "Process with PID {} did not terminate after {} seconds."
  304. .format(pid, timeout)
  305. )