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