u_boot_utils.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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[].
  125. ignore_errors: Indicate whether to ignore errors. If True, the function
  126. will simply return if the command cannot be executed or exits with
  127. an error code, otherwise an exception will be raised if such
  128. problems occur.
  129. Returns:
  130. Nothing.
  131. """
  132. runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
  133. runner.run(cmd, ignore_errors=ignore_errors)
  134. runner.close()
  135. ram_base = None
  136. def find_ram_base(u_boot_console):
  137. """Find the running U-Boot's RAM location.
  138. Probe the running U-Boot to determine the address of the first bank
  139. of RAM. This is useful for tests that test reading/writing RAM, or
  140. load/save files that aren't associated with some standard address
  141. typically represented in an environment variable such as
  142. ${kernel_addr_r}. The value is cached so that it only needs to be
  143. actively read once.
  144. Args:
  145. u_boot_console: A console connection to U-Boot.
  146. Returns:
  147. The address of U-Boot's first RAM bank, as an integer.
  148. """
  149. global ram_base
  150. if u_boot_console.config.buildconfig.get('config_cmd_bdi', 'n') != 'y':
  151. pytest.skip('bdinfo command not supported')
  152. if ram_base == -1:
  153. pytest.skip('Previously failed to find RAM bank start')
  154. if ram_base is not None:
  155. return ram_base
  156. with u_boot_console.log.section('find_ram_base'):
  157. response = u_boot_console.run_command('bdinfo')
  158. for l in response.split('\n'):
  159. if '-> start' in l:
  160. ram_base = int(l.split('=')[1].strip(), 16)
  161. break
  162. if ram_base is None:
  163. ram_base = -1
  164. raise Exception('Failed to find RAM bank start in `bdinfo`')
  165. return ram_base