u_boot_utils.py 11 KB

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