blob: f44442e0c77980b5bf80b92f35c5c67820b129c3 [file] [log] [blame]
Stephen Warren76b46932016-01-22 12:30:12 -07001# SPDX-License-Identifier: GPL-2.0
Tom Rini83d290c2018-05-06 17:58:06 -04002# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
Stephen Warren76b46932016-01-22 12:30:12 -07003
4# Utility code shared across multiple tests.
5
6import hashlib
Stephen Warrenac122ef2017-10-26 18:23:35 -06007import inspect
Stephen Warren76b46932016-01-22 12:30:12 -07008import os
9import os.path
Heiko Schocherb8218a92016-05-09 10:08:24 +020010import pytest
Alper Nebi Yasak99f53032021-06-04 22:04:46 +030011import signal
Stephen Warren76b46932016-01-22 12:30:12 -070012import sys
13import time
Liam Beguinc3342cd2018-03-14 19:15:15 -040014import re
Stephen Warren76b46932016-01-22 12:30:12 -070015
16def md5sum_data(data):
Stephen Warrene8debf32016-01-26 13:41:30 -070017 """Calculate the MD5 hash of some data.
Stephen Warren76b46932016-01-22 12:30:12 -070018
19 Args:
20 data: The data to hash.
21
22 Returns:
23 The hash of the data, as a binary string.
Stephen Warrene8debf32016-01-26 13:41:30 -070024 """
Stephen Warren76b46932016-01-22 12:30:12 -070025
26 h = hashlib.md5()
27 h.update(data)
28 return h.digest()
29
30def md5sum_file(fn, max_length=None):
Stephen Warrene8debf32016-01-26 13:41:30 -070031 """Calculate the MD5 hash of the contents of a file.
Stephen Warren76b46932016-01-22 12:30:12 -070032
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 Warrene8debf32016-01-26 13:41:30 -070041 """
Stephen Warren76b46932016-01-22 12:30:12 -070042
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
51class PersistentRandomFile(object):
Stephen Warrene8debf32016-01-26 13:41:30 -070052 """Generate and store information about a persistent file containing
53 random data."""
Stephen Warren76b46932016-01-22 12:30:12 -070054
55 def __init__(self, u_boot_console, fn, size):
Stephen Warrene8debf32016-01-26 13:41:30 -070056 """Create or process the persistent file.
Stephen Warren76b46932016-01-22 12:30:12 -070057
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 Warrene8debf32016-01-26 13:41:30 -070072 """
Stephen Warren76b46932016-01-22 12:30:12 -070073
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
90def attempt_to_open_file(fn):
Stephen Warrene8debf32016-01-26 13:41:30 -070091 """Attempt to open a file, without throwing exceptions.
Stephen Warren76b46932016-01-22 12:30:12 -070092
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 Warrene8debf32016-01-26 13:41:30 -0700104 """
Stephen Warren76b46932016-01-22 12:30:12 -0700105
106 try:
107 return open(fn, 'rb')
108 except:
109 return None
110
111def wait_until_open_succeeds(fn):
Stephen Warrene8debf32016-01-26 13:41:30 -0700112 """Poll until a file can be opened, or a timeout occurs.
Stephen Warren76b46932016-01-22 12:30:12 -0700113
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 Warrene8debf32016-01-26 13:41:30 -0700122 """
Stephen Warren76b46932016-01-22 12:30:12 -0700123
Paul Burtonb8c45552017-09-14 14:34:44 -0700124 for i in range(100):
Stephen Warren76b46932016-01-22 12:30:12 -0700125 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
131def wait_until_file_open_fails(fn, ignore_errors):
Stephen Warrene8debf32016-01-26 13:41:30 -0700132 """Poll until a file cannot be opened, or a timeout occurs.
Stephen Warren76b46932016-01-22 12:30:12 -0700133
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 Warrene8debf32016-01-26 13:41:30 -0700145 """
Stephen Warren76b46932016-01-22 12:30:12 -0700146
Paul Burtonb8c45552017-09-14 14:34:44 -0700147 for i in range(100):
Stephen Warren76b46932016-01-22 12:30:12 -0700148 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
Simon Glass15156c92021-10-23 17:25:57 -0600157def run_and_log(u_boot_console, cmd, ignore_errors=False, stdin=None):
Stephen Warrene8debf32016-01-26 13:41:30 -0700158 """Run a command and log its output.
Stephen Warren76b46932016-01-22 12:30:12 -0700159
160 Args:
161 u_boot_console: A console connection to U-Boot.
Simon Glassec70f8a2016-07-31 17:35:05 -0600162 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 Warren76b46932016-01-22 12:30:12 -0700165 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.
Simon Glass15156c92021-10-23 17:25:57 -0600169 stdin: Input string to pass to the command as stdin (or None)
Stephen Warren76b46932016-01-22 12:30:12 -0700170
171 Returns:
Simon Glassf3d3e952016-07-03 09:40:39 -0600172 The output as a string.
Stephen Warrene8debf32016-01-26 13:41:30 -0700173 """
Simon Glassec70f8a2016-07-31 17:35:05 -0600174 if isinstance(cmd, str):
175 cmd = cmd.split()
Stephen Warren76b46932016-01-22 12:30:12 -0700176 runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
Simon Glass15156c92021-10-23 17:25:57 -0600177 output = runner.run(cmd, ignore_errors=ignore_errors, stdin=stdin)
Stephen Warren76b46932016-01-22 12:30:12 -0700178 runner.close()
Simon Glassf3d3e952016-07-03 09:40:39 -0600179 return output
Stephen Warren05266102016-01-21 16:05:30 -0700180
Simon Glass9e17b032016-07-03 09:40:41 -0600181def run_and_log_expect_exception(u_boot_console, cmd, retcode, msg):
Simon Glass72f52262016-07-31 17:35:04 -0600182 """Run a command that is expected to fail.
Simon Glass9e17b032016-07-03 09:40:41 -0600183
184 This runs a command and checks that it fails with the expected return code
185 and exception method. If not, an exception is raised.
186
187 Args:
188 u_boot_console: A console connection to U-Boot.
189 cmd: The command to run, as an array of argv[].
190 retcode: Expected non-zero return code from the command.
Simon Glass72f52262016-07-31 17:35:04 -0600191 msg: String that should be contained within the command's output.
Simon Glass9e17b032016-07-03 09:40:41 -0600192 """
193 try:
194 runner = u_boot_console.log.get_runner(cmd[0], sys.stdout)
195 runner.run(cmd)
196 except Exception as e:
Simon Glass7f64b182016-07-31 17:35:03 -0600197 assert(retcode == runner.exit_status)
Simon Glass9e17b032016-07-03 09:40:41 -0600198 assert(msg in runner.output)
199 else:
Simon Glass7f64b182016-07-31 17:35:03 -0600200 raise Exception("Expected an exception with retcode %d message '%s',"
201 "but it was not raised" % (retcode, msg))
Simon Glass9e17b032016-07-03 09:40:41 -0600202 finally:
203 runner.close()
204
Stephen Warren05266102016-01-21 16:05:30 -0700205ram_base = None
206def find_ram_base(u_boot_console):
Stephen Warrene8debf32016-01-26 13:41:30 -0700207 """Find the running U-Boot's RAM location.
Stephen Warren05266102016-01-21 16:05:30 -0700208
209 Probe the running U-Boot to determine the address of the first bank
210 of RAM. This is useful for tests that test reading/writing RAM, or
211 load/save files that aren't associated with some standard address
212 typically represented in an environment variable such as
213 ${kernel_addr_r}. The value is cached so that it only needs to be
214 actively read once.
215
216 Args:
217 u_boot_console: A console connection to U-Boot.
218
219 Returns:
220 The address of U-Boot's first RAM bank, as an integer.
Stephen Warrene8debf32016-01-26 13:41:30 -0700221 """
Stephen Warren05266102016-01-21 16:05:30 -0700222
223 global ram_base
224 if u_boot_console.config.buildconfig.get('config_cmd_bdi', 'n') != 'y':
225 pytest.skip('bdinfo command not supported')
226 if ram_base == -1:
227 pytest.skip('Previously failed to find RAM bank start')
228 if ram_base is not None:
229 return ram_base
230
231 with u_boot_console.log.section('find_ram_base'):
232 response = u_boot_console.run_command('bdinfo')
233 for l in response.split('\n'):
Daniel Schwierzeckd56dd0b2016-07-06 12:44:22 +0200234 if '-> start' in l or 'memstart =' in l:
Stephen Warren05266102016-01-21 16:05:30 -0700235 ram_base = int(l.split('=')[1].strip(), 16)
236 break
237 if ram_base is None:
238 ram_base = -1
239 raise Exception('Failed to find RAM bank start in `bdinfo`')
240
Quentin Schulzabba7632018-07-09 19:16:26 +0200241 # We don't want ram_base to be zero as some functions test if the given
Bin Mengb2c26082020-03-28 07:25:28 -0700242 # address is NULL (0). Besides, on some RISC-V targets the low memory
243 # is protected that prevents S-mode U-Boot from access.
244 # Let's add 2MiB then (size of an ARM LPAE/v8 section).
Quentin Schulzabba7632018-07-09 19:16:26 +0200245
Bin Mengb2c26082020-03-28 07:25:28 -0700246 ram_base += 1024 * 1024 * 2
Quentin Schulzabba7632018-07-09 19:16:26 +0200247
Stephen Warren05266102016-01-21 16:05:30 -0700248 return ram_base
Stephen Warrenac122ef2017-10-26 18:23:35 -0600249
250class PersistentFileHelperCtxMgr(object):
251 """A context manager for Python's "with" statement, which ensures that any
252 generated file is deleted (and hence regenerated) if its mtime is older
253 than the mtime of the Python module which generated it, and gets an mtime
254 newer than the mtime of the Python module which generated after it is
255 generated. Objects of this type should be created by factory function
256 persistent_file_helper rather than directly."""
257
258 def __init__(self, log, filename):
259 """Initialize a new object.
260
261 Args:
262 log: The Logfile object to log to.
263 filename: The filename of the generated file.
264
265 Returns:
266 Nothing.
267 """
268
269 self.log = log
270 self.filename = filename
271
272 def __enter__(self):
273 frame = inspect.stack()[1]
274 module = inspect.getmodule(frame[0])
275 self.module_filename = module.__file__
276 self.module_timestamp = os.path.getmtime(self.module_filename)
277
278 if os.path.exists(self.filename):
279 filename_timestamp = os.path.getmtime(self.filename)
280 if filename_timestamp < self.module_timestamp:
281 self.log.action('Removing stale generated file ' +
282 self.filename)
283 os.unlink(self.filename)
284
285 def __exit__(self, extype, value, traceback):
286 if extype:
287 try:
288 os.path.unlink(self.filename)
289 except:
290 pass
291 return
292 logged = False
293 for i in range(20):
294 filename_timestamp = os.path.getmtime(self.filename)
295 if filename_timestamp > self.module_timestamp:
296 break
297 if not logged:
298 self.log.action(
299 'Waiting for generated file timestamp to increase')
300 logged = True
301 os.utime(self.filename)
302 time.sleep(0.1)
303
304def persistent_file_helper(u_boot_log, filename):
305 """Manage the timestamps and regeneration of a persistent generated
306 file. This function creates a context manager for Python's "with"
307 statement
308
309 Usage:
310 with persistent_file_helper(u_boot_console.log, filename):
311 code to generate the file, if it's missing.
312
313 Args:
314 u_boot_log: u_boot_console.log.
315 filename: The filename of the generated file.
316
317 Returns:
318 A context manager object.
319 """
320
321 return PersistentFileHelperCtxMgr(u_boot_log, filename)
Liam Beguinc3342cd2018-03-14 19:15:15 -0400322
323def crc32(u_boot_console, address, count):
324 """Helper function used to compute the CRC32 value of a section of RAM.
325
326 Args:
327 u_boot_console: A U-Boot console connection.
328 address: Address where data starts.
329 count: Amount of data to use for calculation.
330
331 Returns:
332 CRC32 value
333 """
334
335 bcfg = u_boot_console.config.buildconfig
336 has_cmd_crc32 = bcfg.get('config_cmd_crc32', 'n') == 'y'
337 assert has_cmd_crc32, 'Cannot compute crc32 without CONFIG_CMD_CRC32.'
338 output = u_boot_console.run_command('crc32 %08x %x' % (address, count))
339
340 m = re.search('==> ([0-9a-fA-F]{8})$', output)
341 assert m, 'CRC32 operation failed.'
342
343 return m.group(1)
Alper Nebi Yasak99f53032021-06-04 22:04:46 +0300344
345def waitpid(pid, timeout=60, kill=False):
346 """Wait a process to terminate by its PID
347
348 This is an alternative to a os.waitpid(pid, 0) call that works on
349 processes that aren't children of the python process.
350
351 Args:
352 pid: PID of a running process.
353 timeout: Time in seconds to wait.
354 kill: Whether to forcibly kill the process after timeout.
355
356 Returns:
357 True, if the process ended on its own.
358 False, if the process was killed by this function.
359
360 Raises:
361 TimeoutError, if the process is still running after timeout.
362 """
363 try:
364 for _ in range(timeout):
365 os.kill(pid, 0)
366 time.sleep(1)
367
368 if kill:
369 os.kill(pid, signal.SIGKILL)
370 return False
371
372 except ProcessLookupError:
373 return True
374
375 raise TimeoutError(
376 "Process with PID {} did not terminate after {} seconds."
377 .format(pid, timeout)
378 )