u_boot_utils.py 9.7 KB

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