u_boot_utils.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 os
  7. import os.path
  8. import pytest
  9. import sys
  10. import time
  11. import pytest
  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 xrange(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 xrange(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. return ram_base