blob: dac74e1238be78d740b898c6055d2dbc3a30527d [file] [log] [blame]
David Brazdilee5e25d2020-01-24 14:17:45 +00001#!/usr/bin/env python3
Andrew Scull18834872018-10-12 11:48:09 +01002#
Andrew Walbran692b3252019-03-07 15:51:31 +00003# Copyright 2018 The Hafnium Authors.
Andrew Scull18834872018-10-12 11:48:09 +01004#
Andrew Walbrane959ec12020-06-17 15:01:09 +01005# Use of this source code is governed by a BSD-style
6# license that can be found in the LICENSE file or at
7# https://opensource.org/licenses/BSD-3-Clause.
Andrew Scull18834872018-10-12 11:48:09 +01008
David Brazdil2df24082019-09-05 11:55:08 +01009"""Script which drives invocation of tests and parsing their output to produce
10a results report.
Andrew Scullbc7189d2018-08-14 09:35:13 +010011"""
12
13from __future__ import print_function
14
Andrew Scull3b62f2b2018-08-21 14:26:12 +010015import xml.etree.ElementTree as ET
16
Andrew Scullbc7189d2018-08-14 09:35:13 +010017import argparse
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010018from abc import ABC, abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +010019import collections
Andrew Scull04502e42018-09-03 14:54:52 +010020import datetime
David Brazdil4f9cf9a2020-02-06 17:34:44 +000021import importlib
Andrew Scullbc7189d2018-08-14 09:35:13 +010022import json
23import os
24import re
25import subprocess
26import sys
Andrew Walbran42bf2842020-06-05 18:50:19 +010027import time
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010028import fdt
Olivier Depreze30c36f2022-11-22 11:26:47 +010029import platform
J-Alvesacdbb862023-01-31 17:14:55 +000030import tempfile
Andrew Scullbc7189d2018-08-14 09:35:13 +010031
Olivier Depreze30c36f2022-11-22 11:26:47 +010032MACHINE = platform.machine()
Olivier Depreze30c36f2022-11-22 11:26:47 +010033
Andrew Scull845fc9b2019-04-03 12:44:26 +010034HFTEST_LOG_PREFIX = "[hftest] "
35HFTEST_LOG_FAILURE_PREFIX = "Failure:"
36HFTEST_LOG_FINISHED = "FINISHED"
37
Daniel Boulby61049dc2023-06-16 14:15:21 +010038HFTEST_CTRL_JSON_START = "[hftest_ctrl:json_start]"
39HFTEST_CTRL_JSON_END = "[hftest_ctrl:json_end]"
40
David Brazdil17e76652020-01-29 14:44:19 +000041HFTEST_CTRL_GET_COMMAND_LINE = "[hftest_ctrl:get_command_line]"
42HFTEST_CTRL_FINISHED = "[hftest_ctrl:finished]"
43
David Brazdil2df24082019-09-05 11:55:08 +010044HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
45 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010046DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010047FVP_BINARY = os.path.join(
Olivier Deprez9f4bad42021-06-18 12:19:07 +020048 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMvA_pkg", "models",
Olivier Deprez78d94eb2023-01-31 09:02:32 +000049 "Linux64_armv8l_GCC-9.3" if MACHINE == "aarch64" else "Linux64_GCC-9.3",
50 "FVP_Base_RevC-2xAEMvA")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010051HF_PREBUILTS = os.path.join(HF_ROOT, "prebuilts")
Olivier Deprez78d94eb2023-01-31 09:02:32 +000052QEMU_PREBUILTS = os.path.join(HF_PREBUILTS,
53 "linux-" + ("x64" if MACHINE == "x86_64" else MACHINE),
54 "qemu", "qemu-system-aarch64")
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010055FVP_PREBUILTS_TFA_ROOT = os.path.join(
56 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010057FVP_PREBUILT_DTS = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010058 FVP_PREBUILTS_TFA_ROOT, "fvp-base-gicv3-psci-1t.dts")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010059
Olivier Deprez1b1c4b62023-01-17 09:56:32 +010060FVP_PREBUILT_TFA_SPMD_ROOT = os.path.join(
61 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-spmd", "fvp")
Andrew Scull845fc9b2019-04-03 12:44:26 +010062
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +000063FVP_PREBUILTS_TFA_EL3_SPMC_ROOT = os.path.join(
64 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-el3-spmc")
J-Alves852fe742021-04-22 11:59:55 +010065VM_NODE_REGEX = "vm[1-9]"
66
Olivier Deprez3917deb2023-01-19 11:08:43 +010067QEMU_CPU_MAX = "max,pauth-impdef=true"
68
David Brazdil2df24082019-09-05 11:55:08 +010069def read_file(path):
70 with open(path, "r") as f:
71 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010072
David Brazdil2df24082019-09-05 11:55:08 +010073def write_file(path, to_write, append=False):
74 with open(path, "a" if append else "w") as f:
75 f.write(to_write)
76
77def append_file(path, to_write):
78 write_file(path, to_write, append=True)
79
80def join_if_not_None(*args):
81 return " ".join(filter(lambda x: x, args))
82
J-Alves852fe742021-04-22 11:59:55 +010083def get_vm_node_from_manifest(dts : str):
84 """ Get VM node string from Partition's extension to Partition Manager's
85 manifest."""
86 match = re.search(VM_NODE_REGEX, dts)
87 if not match:
88 raise Exception("Partition's node is not defined in its manifest.")
89 return match.group()
90
91def correct_vm_node(dts: str, node_index : int):
92 """ The vm node is being appended to the Partition Manager manifests.
93 Ideally, these files would be reused accross various test set-ups."""
94 return dts.replace(get_vm_node_from_manifest(dts), f"vm{node_index}")
95
J-Alves8cc7dbb2021-04-16 10:38:48 +010096DT = collections.namedtuple("DT", ["dts", "dtb"])
97
David Brazdil2df24082019-09-05 11:55:08 +010098class ArtifactsManager:
99 """Class which manages folder with test artifacts."""
100
101 def __init__(self, log_dir):
102 self.created_files = []
103 self.log_dir = log_dir
104
105 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +0100106 try:
David Brazdil2df24082019-09-05 11:55:08 +0100107 os.makedirs(self.log_dir)
108 except OSError:
109 if not os.path.isdir(self.log_dir):
110 raise
111 print("Logs saved under", log_dir)
112
113 # Create files expected by the Sponge test result parser.
114 self.sponge_log_path = self.create_file("sponge_log", ".log")
115 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
116
David Brazdil623b6812019-09-09 11:41:08 +0100117 def gen_file_path(self, basename, extension):
118 """Generate path to a file in the log directory."""
119 return os.path.join(self.log_dir, basename + extension)
120
David Brazdil2df24082019-09-05 11:55:08 +0100121 def create_file(self, basename, extension):
122 """Create and touch a new file in the log folder. Ensure that no other
123 file of the same name was created by this instance of ArtifactsManager.
124 """
125 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +0100126 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +0100127
128 # Check that the path is unique.
129 assert(path not in self.created_files)
130 self.created_files += [ path ]
131
132 # Touch file.
133 with open(path, "w") as f:
134 pass
135
136 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100137
David Brazdil623b6812019-09-09 11:41:08 +0100138 def get_file(self, basename, extension):
139 """Return path to a file in the log folder. Assert that it was created
140 by this instance of ArtifactsManager."""
141 path = self.gen_file_path(basename, extension)
142 assert(path in self.created_files)
143 return path
144
Andrew Scullbc7189d2018-08-14 09:35:13 +0100145
David Brazdil2df24082019-09-05 11:55:08 +0100146# Tuple holding the arguments common to all driver constructors.
147# This is to avoid having to pass arguments from subclasses to superclasses.
148DriverArgs = collections.namedtuple("DriverArgs", [
149 "artifacts",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100150 "hypervisor",
151 "spmc",
David Brazdil2df24082019-09-05 11:55:08 +0100152 "initrd",
153 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000154 "cpu",
J-Alves18a25f92021-05-04 17:47:41 +0100155 "partitions",
156 "global_run_name",
Saul Romero42a13632022-12-20 15:13:36 +0000157 "coverage_plugin",
David Brazdil2df24082019-09-05 11:55:08 +0100158 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100159
David Brazdil2df24082019-09-05 11:55:08 +0100160# State shared between the common Driver class and its subclasses during
161# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100162class DriverRunState:
163 def __init__(self, log_path):
164 self.log_path = log_path
165 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000166
David Brazdil7325eaf2019-09-27 13:04:51 +0100167 def set_ret_code(self, ret_code):
168 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000169
David Brazdil0dbb41f2019-09-09 18:03:35 +0100170class DriverRunException(Exception):
171 """Exception thrown if subprocess invoked by a driver returned non-zero
172 status code. Used to fast-exit from a driver command sequence."""
173 pass
174
175
David Brazdil2df24082019-09-05 11:55:08 +0100176class Driver:
177 """Parent class of drivers for all testable platforms."""
178
179 def __init__(self, args):
180 self.args = args
181
David Brazdil623b6812019-09-09 11:41:08 +0100182 def get_run_log(self, run_name):
183 """Return path to the main log of a given test run."""
184 return self.args.artifacts.get_file(run_name, ".log")
185
David Brazdil2df24082019-09-05 11:55:08 +0100186 def start_run(self, run_name):
187 """Hook called by Driver subclasses before they invoke the target
188 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100189 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100190
Andrew Walbranf636b842020-01-10 11:46:12 +0000191 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100192 """Run a subprocess on behalf of a Driver subclass and append its
193 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100194 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100195 with open(run_state.log_path, "a") as f:
196 f.write("$ {}\r\n".format(" ".join(exec_args)))
197 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000198 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100199 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100200 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100201 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100202
David Brazdil0dbb41f2019-09-09 18:03:35 +0100203 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100204 """Hook called by Driver subclasses after they finished running the
205 target platform. `ret_code` argument is the return code of the main
206 command run by the driver. A corresponding log message is printed."""
207 # Decode return code and add a message to the log.
208 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100209 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100210 f.write("\r\n{}{} timed out\r\n".format(
211 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100212 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100213 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100214 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
215 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100216
217 # Append log of this run to full test log.
218 log_content = read_file(run_state.log_path)
219 append_file(
220 self.args.artifacts.sponge_log_path,
221 log_content + "\r\n\r\n")
222 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000223
David Brazdil2df24082019-09-05 11:55:08 +0100224class QemuDriver(Driver):
225 """Driver which runs tests in QEMU."""
226
Andrew Walbranf636b842020-01-10 11:46:12 +0000227 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100228 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000229 self.qemu_wd = qemu_wd
230 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100231
David Brazdila2358d42020-01-27 18:51:38 +0000232 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100233 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100234 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000235 # If no CPU configuration is selected, then test against the maximum
236 # configuration, "max", supported by QEMU.
Olivier Deprez3917deb2023-01-19 11:08:43 +0100237 if not self.args.cpu or self.args.cpu == "max":
238 cpu = QEMU_CPU_MAX
239 else:
240 cpu = self.args.cpu
241
David Brazdil2df24082019-09-05 11:55:08 +0100242 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100243 "timeout", "--foreground", time_limit,
Olivier Depreze30c36f2022-11-22 11:26:47 +0100244 QEMU_PREBUILTS,
Olivier Deprez5373f232022-11-23 09:57:19 +0100245 "-no-reboot", "-machine", "virt-6.2,virtualization=on,gic-version=3",
J-Alves871e3732022-05-31 17:10:50 +0100246 "-cpu", cpu, "-smp", "8", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100247 "-nographic", "-nodefaults", "-serial", "stdio",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100248 "-d", "unimp", "-kernel", os.path.abspath(self.args.hypervisor),
David Brazdil2df24082019-09-05 11:55:08 +0100249 ]
250
Andrew Walbranf636b842020-01-10 11:46:12 +0000251 if self.tfa:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100252 bl1_path = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +0100253 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100254 "qemu", "bl1.bin")
Andrew Walbranf636b842020-01-10 11:46:12 +0000255 exec_args += ["-bios",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100256 os.path.abspath(bl1_path),
257 "-machine", "secure=on", "-semihosting-config",
Andrew Walbranab4b2d52020-06-11 16:54:10 +0100258 "enable=on,target=native"]
Andrew Walbranf636b842020-01-10 11:46:12 +0000259
David Brazdil2df24082019-09-05 11:55:08 +0100260 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000261 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100262
263 vm_args = join_if_not_None(self.args.vm_args, test_args)
264 if vm_args:
265 exec_args += ["-append", vm_args]
266
267 return exec_args
268
J-Alves67c31912023-02-02 13:52:50 +0000269 def run(self, run_name, test_args, is_long_running, debug = False,
270 show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100271 """Run test given by `test_args` in QEMU."""
J-Alves67c31912023-02-02 13:52:50 +0000272 # TODO: use 'debug' and 'show_output' flags.
David Brazdil2df24082019-09-05 11:55:08 +0100273 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100274
275 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100276 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000277 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000278 self.exec_logged(run_state, exec_args,
279 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100280 except DriverRunException:
281 pass
282
283 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100284
David Brazdil94fd1e92020-02-03 16:45:20 +0000285 def finish(self):
286 """Clean up after running tests."""
287 pass
288
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100289class FvpDriver(Driver, ABC):
290 """Base class for driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100291
J-Alves19216692023-05-12 15:01:31 +0100292 def __init__(self, args, cpu_start_address, fvp_prebuilt_bl31):
Saul Romero42a13632022-12-20 15:13:36 +0000293 self.cov_plugin = args.coverage_plugin or None
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000294 if args.cpu:
295 raise ValueError("FVP emulator does not support the --cpu option.")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100296 super().__init__(args)
J-Alves19216692023-05-12 15:01:31 +0100297 self._cpu_start_address = cpu_start_address
298 self._fvp_prebuilt_bl31 = fvp_prebuilt_bl31
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100299
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100300 def create_dt(self, run_name : str):
301 """Create DT related files, and return respective paths in a tuple
302 (dts,dtb)"""
J-Alves8cc7dbb2021-04-16 10:38:48 +0100303 return DT(self.args.artifacts.create_file(run_name, ".dts"),
304 self.args.artifacts.create_file(run_name, ".dtb"))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100305
J-Alves8cc7dbb2021-04-16 10:38:48 +0100306 def compile_dt(self, run_state, dt : DT):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100307 """Compile DT calling dtc."""
308 dtc_args = [
J-Alves8cc7dbb2021-04-16 10:38:48 +0100309 DTC_SCRIPT, "compile", "-i", dt.dts, "-o", dt.dtb,
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100310 ]
311 self.exec_logged(run_state, dtc_args)
312
313 def create_uart_log(self, run_name : str, file_name : str):
314 """Create uart log file, and return path"""
315 return self.args.artifacts.create_file(run_name, file_name)
316
317 def get_img_and_ldadd(self, partitions : dict):
318 ret = []
319 for i, p in enumerate(partitions):
J-Alves852fe742021-04-22 11:59:55 +0100320 with open(p["dts"], "r") as dt:
321 dts = dt.read()
322 manifest = fdt.parse_dts(dts)
323 vm_node = get_vm_node_from_manifest(dts)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100324 load_address = manifest.get_property("load_address",
J-Alves852fe742021-04-22 11:59:55 +0100325 f"/hypervisor/{vm_node}").value
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100326 ret.append((p["img"], load_address))
327 return ret
328
329 def get_manifests_from_json(self, partitions : list):
330 manifests = ""
331 if partitions is not None:
J-Alves852fe742021-04-22 11:59:55 +0100332 for i, p in enumerate(partitions):
333 manifests += correct_vm_node(read_file(p["dts"]), i + 1)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100334 return manifests
335
336 @abstractmethod
J-Alves8cc7dbb2021-04-16 10:38:48 +0100337 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100338 """Abstract method to generate dts file. This specific to the use case
339 so should be implemented within derived driver"""
340 pass
341
342 @abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +0100343 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000344 self, is_long_running, uart0_log_path, uart1_log_path, dt,
345 debug = False, show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100346 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000347 show_output = debug or show_output
Madhukar Pappireddycc544be2023-10-18 15:01:58 -0500348 time_limit = "100s" if is_long_running else "40s"
J-Alves67c31912023-02-02 13:52:50 +0000349 fvp_args = []
350
351 if not show_output:
352 fvp_args = [
353 "timeout", "--foreground", time_limit,
354 ]
355
356 fvp_args += [
David Brazdil2df24082019-09-05 11:55:08 +0100357 FVP_BINARY,
J-Alves10446d82021-04-26 11:52:57 +0100358 "-C", "pci.pci_smmuv3.mmu.SMMU_AIDR=2",
359 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR0=0x0046123B",
360 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR1=0x00600002",
361 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR3=0x1714",
362 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR5=0xFFFF0472",
363 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR1=0xA0000002",
364 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR2=0",
365 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR3=0",
David Brazdil2df24082019-09-05 11:55:08 +0100366 "-C", "pctl.startup=0.0.0.0",
Olivier Deprezcd857002022-05-09 09:06:24 +0200367 "-C", "bp.secure_memory=1",
David Brazdil2df24082019-09-05 11:55:08 +0100368 "-C", "cluster0.NUM_CORES=4",
369 "-C", "cluster1.NUM_CORES=4",
370 "-C", "cache_state_modelled=0",
David Brazdil2df24082019-09-05 11:55:08 +0100371 "-C", "bp.vis.rate_limit-enable=false",
David Brazdil2df24082019-09-05 11:55:08 +0100372 "-C", "bp.pl011_uart0.untimed_fifos=1",
373 "-C", "bp.pl011_uart0.unbuffered_output=1",
J-Alves19216692023-05-12 15:01:31 +0100374 "-C", f"cluster0.cpu0.RVBAR={self._cpu_start_address}",
375 "-C", f"cluster0.cpu1.RVBAR={self._cpu_start_address}",
376 "-C", f"cluster0.cpu2.RVBAR={self._cpu_start_address}",
377 "-C", f"cluster0.cpu3.RVBAR={self._cpu_start_address}",
378 "-C", f"cluster1.cpu0.RVBAR={self._cpu_start_address}",
379 "-C", f"cluster1.cpu1.RVBAR={self._cpu_start_address}",
380 "-C", f"cluster1.cpu2.RVBAR={self._cpu_start_address}",
381 "-C", f"cluster1.cpu3.RVBAR={self._cpu_start_address}",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100382 "--data",
J-Alves19216692023-05-12 15:01:31 +0100383 f"cluster0.cpu0={self._fvp_prebuilt_bl31}@{self._cpu_start_address}",
David Brazdil2df24082019-09-05 11:55:08 +0100384 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
Raghu Krishnamurthy75ebf8c2021-11-28 07:22:12 -0800385 "-C", "cluster0.has_arm_v8-5=1",
386 "-C", "cluster1.has_arm_v8-5=1",
387 "-C", "cluster0.has_branch_target_exception=1",
388 "-C", "cluster1.has_branch_target_exception=1",
Maksims Svecovsce1261f2022-03-04 15:22:58 +0000389 "-C", "cluster0.memory_tagging_support_level=2",
390 "-C", "cluster1.memory_tagging_support_level=2",
391 "-C", "bp.dram_metadata.is_enabled=1",
Raghu Krishnamurthye2eae292022-08-10 22:38:41 -0700392 "-C", "cluster0.gicv3.extended-interrupt-range-support=1",
393 "-C", "cluster1.gicv3.extended-interrupt-range-support=1",
394 "-C", "gic_distributor.extended-ppi-count=64",
395 "-C", "gic_distributor.extended-spi-count=1024",
396 "-C", "gic_distributor.ARE-fixed-to-one=1",
David Brazdil2df24082019-09-05 11:55:08 +0100397 ]
J-Alves18a25f92021-05-04 17:47:41 +0100398
399 if uart0_log_path and uart1_log_path:
400 fvp_args += [
401 "-C", f"bp.pl011_uart0.out_file={uart0_log_path}",
402 "-C", f"bp.pl011_uart1.out_file={uart1_log_path}",
403 ]
J-Alves67c31912023-02-02 13:52:50 +0000404
405 if not show_output:
406 fvp_args += [
407 "-C", "bp.vis.disable_visualisation=true",
408 "-C", "bp.terminal_0.start_telnet=false",
409 "-C", "bp.terminal_1.start_telnet=false",
410 "-C", "bp.terminal_2.start_telnet=false",
411 "-C", "bp.terminal_3.start_telnet=false",
412 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
413 ]
414
415 if debug:
416 fvp_args += [
Saul Romero42a13632022-12-20 15:13:36 +0000417 "-I", "-p"
418 ]
419
420 if self.cov_plugin is not None:
421 fvp_args += [
422 "--plugin", self.cov_plugin
J-Alves67c31912023-02-02 13:52:50 +0000423 ]
David Brazdil2df24082019-09-05 11:55:08 +0100424 return fvp_args
425
J-Alves67c31912023-02-02 13:52:50 +0000426 def run(self, run_name, test_args, is_long_running, debug = False,
427 show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100428 """ Run test """
David Brazdil2df24082019-09-05 11:55:08 +0100429 run_state = self.start_run(run_name)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100430 dt = self.create_dt(run_name)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100431 uart0_log_path = self.create_uart_log(run_name, ".uart0.log")
432 uart1_log_path = self.create_uart_log(run_name, ".uart1.log")
David Brazdil2df24082019-09-05 11:55:08 +0100433
David Brazdil0dbb41f2019-09-09 18:03:35 +0100434 try:
J-Alves8cc7dbb2021-04-16 10:38:48 +0100435 self.gen_dts(dt, test_args)
436 self.compile_dt(run_state, dt)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100437 fvp_args = self.gen_fvp_args(is_long_running, uart0_log_path,
J-Alves67c31912023-02-02 13:52:50 +0000438 uart1_log_path, dt, debug=debug,
439 show_output=show_output)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100440 self.exec_logged(run_state, fvp_args)
441 except DriverRunException:
442 pass
David Brazdil2df24082019-09-05 11:55:08 +0100443
444 # Append UART0 output to main log.
445 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100446 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100447
David Brazdil94fd1e92020-02-03 16:45:20 +0000448 def finish(self):
449 """Clean up after running tests."""
450 pass
451
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100452class FvpDriverHypervisor(FvpDriver):
453 """
454 Driver which runs tests in Arm FVP emulator, with hafnium as hypervisor
455 """
456 INITRD_START= 0x84000000
Olivier Depreza516f482021-04-30 18:47:59 +0200457 INITRD_END = 0x86000000 #Default value, however may change if initrd in args
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100458
J-Alves19216692023-05-12 15:01:31 +0100459 def __init__(self, args, hypervisor_address=0x80000000, hypervisor_dtb_address=0x82000000):
460 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILTS_TFA_ROOT, "bl31.bin")
461 FvpDriver.__init__(self, args, 0x04020000, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100462 self.vms_in_partitions_json = args.partitions and args.partitions["VMs"]
J-Alves19216692023-05-12 15:01:31 +0100463 self._hypervisor_address = hypervisor_address
464 self._hypervisor_dtb_address = hypervisor_dtb_address
J-Alves38223dd2021-04-20 17:31:48 +0100465
J-Alves8cc7dbb2021-04-16 10:38:48 +0100466 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100467 """Create a DeviceTree source which will be compiled into a DTB and
468 passed to FVP for a test run."""
469
470 vm_args = join_if_not_None(self.args.vm_args, test_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100471 write_file(dt.dts, read_file(FVP_PREBUILT_DTS))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100472
473 # Write the vm arguments to the partition manifest
474 to_append = f"""
475/ {{
476 chosen {{
477 bootargs = "{vm_args}";
478 stdout-path = "serial0:115200n8";
479 linux,initrd-start = <{self.INITRD_START if self.args.initrd else 0}>;
480 linux,initrd-end = <{self.INITRD_END if self.args.initrd else 0}>;
481 }};
482}};"""
483 if self.vms_in_partitions_json:
484 to_append += self.get_manifests_from_json(self.args.partitions["VMs"])
485
J-Alves8cc7dbb2021-04-16 10:38:48 +0100486 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100487
488 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000489 self, is_long_running, uart0_log_path, uart1_log_path, dt,
490 debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100491 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000492 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt,
493 debug, show_output)
494 fvp_args = FvpDriver.gen_fvp_args(*common_args)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100495
J-Alves8cc7dbb2021-04-16 10:38:48 +0100496 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100497 "--data", f"cluster0.cpu0={dt.dtb}@{self._hypervisor_dtb_address}",
498 "--data", f"cluster0.cpu0={self.args.hypervisor}@{self._hypervisor_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100499 ]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100500
501 if self.vms_in_partitions_json:
502 img_ldadd = self.get_img_and_ldadd(self.args.partitions["VMs"])
503 for img, ldadd in img_ldadd:
504 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
505
506 if self.args.initrd:
507 fvp_args += [
508 "--data",
509 f"cluster0.cpu0={self.args.initrd}@{self.INITRD_START}"
510 ]
511 return fvp_args
512
513class FvpDriverSPMC(FvpDriver):
514 """
515 Driver which runs tests in Arm FVP emulator, with hafnium as SPMC
516 """
517 FVP_PREBUILT_SECURE_DTS = os.path.join(
518 HF_ROOT, "test", "vmapi", "fvp-base-spmc.dts")
J-Alvesacdbb862023-01-31 17:14:55 +0000519 hftest_cmd_file = tempfile.NamedTemporaryFile(mode="w+")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100520
J-Alves19216692023-05-12 15:01:31 +0100521 def __init__(self, args, cpu_start_address=0x04010000, fvp_prebuilt_bl31=None):
522 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILT_TFA_SPMD_ROOT, "bl31.bin") if fvp_prebuilt_bl31 is None else fvp_prebuilt_bl31
523 super().__init__(args, cpu_start_address, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100524
J-Alves19216692023-05-12 15:01:31 +0100525 self._spmc_address = 0x6000000
526 self._spmc_dtb_address = 0x0403f000
J-Alves38223dd2021-04-20 17:31:48 +0100527
J-Alves8cc7dbb2021-04-16 10:38:48 +0100528 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100529 """Create a DeviceTree source which will be compiled into a DTB and
530 passed to FVP for a test run."""
531 to_append = self.get_manifests_from_json(self.args.partitions["SPs"])
J-Alves8cc7dbb2021-04-16 10:38:48 +0100532 write_file(dt.dts, read_file(FvpDriverSPMC.FVP_PREBUILT_SECURE_DTS))
533 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100534
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000535 def secure_ctrl_fvp_args(self, secure_ctrl):
536 fvp_args = ""
537 if secure_ctrl:
538 fvp_args = [
539 "-C", f"bp.pl011_uart0.in_file={FvpDriverSPMC.hftest_cmd_file.name}",
540 "-C", f"bp.pl011_uart0.shutdown_tag=\"{HFTEST_CTRL_FINISHED}\"",
541 ]
542 return fvp_args
543
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100544 def gen_fvp_args(
J-Alves8cc7dbb2021-04-16 10:38:48 +0100545 self, is_long_running, uart0_log_path, uart1_log_path, dt,
J-Alves67c31912023-02-02 13:52:50 +0000546 call_super = True, secure_ctrl = True, debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100547 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000548 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
549 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100550 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
J-Alves8cc7dbb2021-04-16 10:38:48 +0100551
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100552 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100553 "--data", f"cluster0.cpu0={dt.dtb}@{self._spmc_dtb_address}",
554 "--data", f"cluster0.cpu0={self.args.spmc}@{self._spmc_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100555 ]
556
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000557 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
J-Alves18a25f92021-05-04 17:47:41 +0100558
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100559 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
560 for img, ldadd in img_ldadd:
561 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
562
563 return fvp_args
564
J-Alves67c31912023-02-02 13:52:50 +0000565 def run(self, run_name, test_args, is_long_running, debug = False, show_output = False):
J-Alvesacdbb862023-01-31 17:14:55 +0000566 vm_args = join_if_not_None(self.args.vm_args, test_args)
567 FvpDriverSPMC.hftest_cmd_file.write(f"{vm_args}\n")
568 FvpDriverSPMC.hftest_cmd_file.seek(0)
J-Alves67c31912023-02-02 13:52:50 +0000569 return super().run(run_name, test_args, is_long_running, debug, show_output)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100570
571 def finish(self):
572 """Clean up after running tests."""
J-Alvesacdbb862023-01-31 17:14:55 +0000573 FvpDriverSPMC.hftest_cmd_file.close()
David Brazdil2df24082019-09-05 11:55:08 +0100574
J-Alves38223dd2021-04-20 17:31:48 +0100575class FvpDriverBothWorlds(FvpDriverHypervisor, FvpDriverSPMC):
576 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100577 FvpDriverHypervisor.__init__(self, args, hypervisor_address=0x88000000)
J-Alves38223dd2021-04-20 17:31:48 +0100578 FvpDriverSPMC.__init__(self, args)
579
J-Alves38223dd2021-04-20 17:31:48 +0100580 def create_dt(self, run_name):
581 dt = dict()
582 dt["hypervisor"] = FvpDriver.create_dt(self, run_name + "_hypervisor")
583 dt["spmc"] = FvpDriver.create_dt(self, run_name + "_spmc")
584 return dt
585
J-Alves38223dd2021-04-20 17:31:48 +0100586 def compile_dt(self, run_state, dt):
587 FvpDriver.compile_dt(self, run_state, dt["hypervisor"])
588 FvpDriver.compile_dt(self, run_state, dt["spmc"])
589
590 def gen_dts(self, dt, test_args):
591 FvpDriverHypervisor.gen_dts(self, dt["hypervisor"], test_args)
592 FvpDriverSPMC.gen_dts(self, dt["spmc"], test_args)
593
J-Alves67c31912023-02-02 13:52:50 +0000594 def gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
595 debug = False, show_output = False):
J-Alves38223dd2021-04-20 17:31:48 +0100596 """Generate command line arguments for FVP."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000597 common_args = (self, is_long_running, uart0_log_path, uart1_log_path)
J-Alves67c31912023-02-02 13:52:50 +0000598 fvp_args = FvpDriverHypervisor.gen_fvp_args(*common_args, dt["hypervisor"],
599 debug, show_output)
J-Alves18a25f92021-05-04 17:47:41 +0100600 fvp_args += FvpDriverSPMC.gen_fvp_args(*common_args, dt["spmc"], False,
601 False)
J-Alves8d9fbb92021-12-13 17:28:15 +0000602 return fvp_args
J-Alves18a25f92021-05-04 17:47:41 +0100603
J-Alves67c31912023-02-02 13:52:50 +0000604 def run(self, run_name, test_args, is_long_running, debug = False,
605 show_output = False):
606
607 return FvpDriver.run(self, run_name, test_args, is_long_running,
608 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100609
610 def finish(self):
611 """Clean up after running tests."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000612 FvpDriver.finish(self)
J-Alves38223dd2021-04-20 17:31:48 +0100613
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000614class FvpDriverEL3SPMC(FvpDriverSPMC):
615 """
616 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
617 """
618
619 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100620 FvpDriverSPMC.__init__(
621 self, args, cpu_start_address=0x04003000,
622 fvp_prebuilt_bl31=os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl31.bin"))
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000623 self.vms_in_partitions_json = args.partitions and args.partitions["SPs"]
J-Alves19216692023-05-12 15:01:31 +0100624 self._sp_dtb_address = 0x0403f000
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000625
626 def sp_partition_manifest_fvp_args(self):
627 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
628
629 # Expect only one tuple with img and load address, as EL3 SPMC only supports
630 # one SP.
631 assert(len(img_ldadd) == 1)
632 img, ldadd = img_ldadd[0]
633 fvp_args = ["--data", f"cluster0.cpu0={img}@{ldadd}"]
634
635 # Even though FF-A manifest is part of the SP PKG we need to load at a specific
636 # location. Fetch the respective dtb file and load at the following address.
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000637 output_path = os.path.dirname(os.path.dirname(img))
638 partition_manifest = f"{output_path}/partition-manifest.dtb"
J-Alves19216692023-05-12 15:01:31 +0100639 fvp_args += ["--data", f"cluster0.cpu0={partition_manifest}@{self._sp_dtb_address}"]
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000640 return fvp_args
641
642 def gen_fvp_args(
643 self, is_long_running, uart0_log_path, uart1_log_path, dt,
644 call_super = True, secure_ctrl = True, debug = False, show_output = False):
645 """Generate command line arguments for FVP."""
646 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
647 debug, show_output)
648 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
649
650 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
651
652 fvp_args += self.sp_partition_manifest_fvp_args()
653
654 return fvp_args
655
Shruti Gupta22dbef32023-04-03 10:26:31 +0100656class FvpDriverEL3SPMCBothWorlds(FvpDriverHypervisor, FvpDriverEL3SPMC):
657 """
658 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
659 """
660
J-Alves19216692023-05-12 15:01:31 +0100661 def __init__(self, args):
662 FvpDriverHypervisor.__init__(self, args)
663 FvpDriverEL3SPMC.__init__(self, args)
Shruti Gupta22dbef32023-04-03 10:26:31 +0100664
J-Alves19216692023-05-12 15:01:31 +0100665 self._fvp_prebuilt_bl32 = os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl32.bin")
666 self._fvp_prebuilt_dtb = os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "fdts/fvp_tsp_sp_manifest.dtb")
Shruti Gupta22dbef32023-04-03 10:26:31 +0100667
668 def gen_fvp_args(
669 self, is_long_running, uart0_log_path, uart1_log_path, dt,
670 call_super = True, secure_ctrl = True, debug = False, show_output = False):
671 """Generate command line arguments for FVP."""
672
673 fvp_args = FvpDriverHypervisor.gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
674 debug, show_output)
675
676 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
677
678 if self.args.partitions is not None and self.args.partitions["SPs"] is not None:
679 fvp_args += FvpDriverEL3SPMC.sp_partition_manifest_fvp_args(self)
680 else :
681 # Use prebuilt TSP and TSP manifest if build does not specify SP
682 # EL3 SPMC expects SP to be loaded at 0xFF200000 and SP manifest at 0x0403F000
J-Alves19216692023-05-12 15:01:31 +0100683 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_bl32}@0xff200000"]
684 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_dtb}@{self._sp_dtb_address}"]
Shruti Gupta22dbef32023-04-03 10:26:31 +0100685
686 return fvp_args
687
David Brazdil17e76652020-01-29 14:44:19 +0000688class SerialDriver(Driver):
689 """Driver which communicates with a device over the serial port."""
690
David Brazdil9d4ed962020-02-06 17:23:48 +0000691 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000692 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000693 self.tty_file = tty_file
694 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000695 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000696
David Brazdil9d4ed962020-02-06 17:23:48 +0000697 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000698 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000699
David Brazdil9d4ed962020-02-06 17:23:48 +0000700 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000701 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000702
David Brazdil17e76652020-01-29 14:44:19 +0000703 def run(self, run_name, test_args, is_long_running):
704 """Communicate `test_args` to the device over the serial port."""
705 run_state = self.start_run(run_name)
706
David Brazdil9d4ed962020-02-06 17:23:48 +0000707 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000708 with open(run_state.log_path, "a") as f:
709 while True:
710 # Read one line from the serial port.
711 line = ser.readline().decode('utf-8')
712 if len(line) == 0:
713 # Timeout
714 run_state.set_ret_code(124)
715 input("Timeout. " +
716 "Press ENTER and then reset the device...")
717 break
718 # Write the line to the log file.
719 f.write(line)
720 if HFTEST_CTRL_GET_COMMAND_LINE in line:
721 # Device is waiting for `test_args`.
722 ser.write(test_args.encode('ascii'))
723 ser.write(b'\r')
724 elif HFTEST_CTRL_FINISHED in line:
725 # Device has finished running this test and will reboot.
726 break
J-Alves18a25f92021-05-04 17:47:41 +0100727
David Brazdil17e76652020-01-29 14:44:19 +0000728 return self.finish_run(run_state)
729
David Brazdil94fd1e92020-02-03 16:45:20 +0000730 def finish(self):
731 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000732 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000733 while True:
734 line = ser.readline().decode('utf-8')
735 if len(line) == 0:
736 input("Timeout. Press ENTER and then reset the device...")
737 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
738 # Device is waiting for a command. Instruct it to exit
739 # the test environment.
740 ser.write("exit".encode('ascii'))
741 ser.write(b'\r')
742 break
743
David Brazdil2df24082019-09-05 11:55:08 +0100744# Tuple used to return information about the results of running a set of tests.
745TestRunnerResult = collections.namedtuple("TestRunnerResult", [
746 "tests_run",
747 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100748 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100749 ])
750
David Brazdil2df24082019-09-05 11:55:08 +0100751class TestRunner:
752 """Class which communicates with a test platform to obtain a list of
753 available tests and driving their execution."""
754
J-Alves8cc7dbb2021-04-16 10:38:48 +0100755 def __init__(self, artifacts, driver, test_set_up, suite_regex, test_regex,
J-Alves67c31912023-02-02 13:52:50 +0000756 skip_long_running_tests, force_long_running, debug, show_output):
David Brazdil2df24082019-09-05 11:55:08 +0100757 self.artifacts = artifacts
758 self.driver = driver
J-Alves8cc7dbb2021-04-16 10:38:48 +0100759 self.test_set_up = test_set_up
David Brazdil3cc24aa2019-09-27 10:24:41 +0100760 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100761 self.force_long_running = force_long_running
J-Alves67c31912023-02-02 13:52:50 +0000762 self.debug = debug
763 self.show_output = show_output
David Brazdil2df24082019-09-05 11:55:08 +0100764
765 self.suite_re = re.compile(suite_regex or ".*")
766 self.test_re = re.compile(test_regex or ".*")
767
768 def extract_hftest_lines(self, raw):
769 """Extract hftest-specific lines from a raw output from an invocation
770 of the test platform."""
771 lines = []
J-Alves07be7bb2021-04-13 11:09:12 +0100772 lines_to_process = raw.splitlines()
773
774 try:
775 # If logs have logs of more than one VM, the loop below to extract
776 # lines won't work. Thus, extracting between starting and ending
777 # logs: HFTEST_CTRL_GET_COMMAND_LINE and HFTEST_CTRL_FINISHED.
778 hftest_start = lines_to_process.index(HFTEST_CTRL_GET_COMMAND_LINE) + 1
779 hftest_end = lines_to_process.index(HFTEST_CTRL_FINISHED)
780 except ValueError:
781 hftest_start = 0
782 hftest_end = len(lines_to_process)
783
784 lines_to_process = lines_to_process[hftest_start : hftest_end]
785
786 for line in lines_to_process:
J-Alvesb882db92023-08-02 13:40:07 +0100787 match = re.search(f"^(VM|SP) \d+: ", line)
J-Alves3dbb8562020-12-01 10:45:37 +0000788 if match is not None:
789 line = line[match.end():]
David Brazdil2df24082019-09-05 11:55:08 +0100790 if line.startswith(HFTEST_LOG_PREFIX):
791 lines.append(line[len(HFTEST_LOG_PREFIX):])
792 return lines
793
794 def get_test_json(self):
795 """Invoke the test platform and request a JSON of available test and
796 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100797 out = self.driver.run("json", "json", self.force_long_running)
Daniel Boulby61049dc2023-06-16 14:15:21 +0100798 hf_out = self.extract_hftest_lines(out)
799 hf_out = hf_out[hf_out.index(HFTEST_CTRL_JSON_START) + 1
800 :hf_out.index(HFTEST_CTRL_JSON_END)];
801 hf_out = "\n".join(hf_out)
David Brazdil2df24082019-09-05 11:55:08 +0100802 try:
803 return json.loads(hf_out)
804 except ValueError as e:
805 print(out)
806 raise e
807
808 def collect_results(self, fn, it, xml_node):
809 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
810 Insert "tests" and "failures" nodes to `xml_node`."""
811 tests_run = 0
812 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100813 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100814 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100815 for i in it:
816 sub_result = fn(i)
817 assert(sub_result.tests_run >= sub_result.tests_failed)
818 tests_run += sub_result.tests_run
819 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100820 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100821 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100822
Andrew Walbranf9463922020-06-05 16:44:42 +0100823 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100824 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100825 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100826 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100827 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100828
829 def is_passed_test(self, test_out):
830 """Parse the output of a test and return True if it passed."""
831 return \
832 len(test_out) > 0 and \
833 test_out[-1] == HFTEST_LOG_FINISHED and \
834 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
835
Andrew Walbranf9463922020-06-05 16:44:42 +0100836 def get_failure_message(self, test_out):
837 """Parse the output of a test and return the message of the first
838 assertion failure."""
839 for i, line in enumerate(test_out):
840 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
841 # The assertion message is on the line after the 'Failure:'
842 return test_out[i + 1].strip()
843
844 return None
845
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000846 def get_log_name(self, suite, test):
847 """Returns a string with a generated log name for the test."""
848 log_name = ""
849
850 cpu = self.driver.args.cpu
851 if cpu:
852 log_name += cpu + "."
853
854 log_name += suite["name"] + "." + test["name"]
855
856 return log_name
857
David Brazdil2df24082019-09-05 11:55:08 +0100858 def run_test(self, suite, test, suite_xml):
859 """Invoke the test platform and request to run a given `test` in given
860 `suite`. Create a new XML node with results under `suite_xml`.
861 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100862 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100863 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100864
865 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100866 test_xml.set("name", test["name"])
867 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100868
J-Alvesd459b562022-12-05 14:56:33 +0000869 if (self.skip_long_running_tests and test["is_long_running"]) or test["skip_test"]:
Andrew Walbranf9463922020-06-05 16:44:42 +0100870 print(" SKIP", test["name"])
871 test_xml.set("status", "notrun")
872 skipped_xml = ET.SubElement(test_xml, "skipped")
873 skipped_xml.set("message", "Long running")
874 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
875
J-Alves67c31912023-02-02 13:52:50 +0000876 action_log = "DEBUG" if self.debug else "RUN"
877 print(f" {action_log}", test["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100878 log_name = self.get_log_name(suite, test)
879
David Brazdil2df24082019-09-05 11:55:08 +0100880 test_xml.set("status", "run")
881
Andrew Walbran42bf2842020-06-05 18:50:19 +0100882 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100883 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100884 log_name, "run {} {}".format(suite["name"], test["name"]),
J-Alves67c31912023-02-02 13:52:50 +0000885 test["is_long_running"] or self.force_long_running,
886 self.debug, self.show_output)
887
Andrew Walbranf9463922020-06-05 16:44:42 +0100888 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100889 elapsed_time = time.perf_counter() - start_time
890
891 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100892
Andrew Walbranf9463922020-06-05 16:44:42 +0100893 system_out_xml = ET.SubElement(test_xml, "system-out")
894 system_out_xml.text = out
895
896 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100897 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100898 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100899 else:
David Brazdil623b6812019-09-09 11:41:08 +0100900 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100901 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100902 failure_message = self.get_failure_message(hftest_out) or "Test failed"
903 failure_xml.set("message", failure_message)
904 failure_xml.text = '\n'.join(hftest_out)
905 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100906
907 def run_suite(self, suite, xml):
908 """Invoke the test platform and request to run all matching tests in
909 `suite`. Create new XML nodes with results under `xml`.
910 Suite skipped if it does not match the regex given to constructor."""
911 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100912 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100913
914 print(" SUITE", suite["name"])
915 suite_xml = ET.SubElement(xml, "testsuite")
916 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100917 properties_xml = ET.SubElement(suite_xml, "properties")
918
919 property_xml = ET.SubElement(properties_xml, "property")
920 property_xml.set("name", "driver")
921 property_xml.set("value", type(self.driver).__name__)
922
923 if self.driver.args.cpu:
924 property_xml = ET.SubElement(properties_xml, "property")
925 property_xml.set("name", "cpu")
926 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100927
928 return self.collect_results(
929 lambda test: self.run_test(suite, test, suite_xml),
930 suite["tests"],
931 suite_xml)
932
933 def run_tests(self):
934 """Run all suites and tests matching regexes given to constructor.
935 Write results to sponge log XML. Return the number of run and failed
936 tests."""
937
938 test_spec = self.get_test_json()
939 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
940
941 xml = ET.Element("testsuites")
J-Alves8cc7dbb2021-04-16 10:38:48 +0100942 xml.set("name", self.test_set_up)
David Brazdil2df24082019-09-05 11:55:08 +0100943 xml.set("timestamp", timestamp)
944
945 result = self.collect_results(
946 lambda suite: self.run_suite(suite, xml),
947 test_spec["suites"],
948 xml)
949
950 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000951 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
952 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100953
954 if result.tests_failed > 0:
955 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
956 "tests failed")
957 elif result.tests_run > 0:
958 print(" PASS: all", result.tests_run, "tests passed")
959
David Brazdil94fd1e92020-02-03 16:45:20 +0000960 # Let the driver clean up.
961 self.driver.finish()
962
David Brazdil2df24082019-09-05 11:55:08 +0100963 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100964
Andrew Scullbc7189d2018-08-14 09:35:13 +0100965def Main():
966 parser = argparse.ArgumentParser()
J-Alves8cc7dbb2021-04-16 10:38:48 +0100967 parser.add_argument("--hypervisor")
968 parser.add_argument("--spmc")
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000969 parser.add_argument("--el3_spmc", action="store_true")
Andrew Scull23e93a82018-10-26 14:56:04 +0100970 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100971 parser.add_argument("--out_initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100972 parser.add_argument("--out_partitions")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000973 parser.add_argument("--initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100974 parser.add_argument("--partitions_json")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100975 parser.add_argument("--suite")
976 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000977 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000978 parser.add_argument("--driver", default="qemu")
979 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
980 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000981 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100982 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100983 parser.add_argument("--force-long-running", action="store_true")
J-Alves67c31912023-02-02 13:52:50 +0000984 parser.add_argument("--debug", action="store_true",
985 help="Makes platforms stall waiting for debugger connection.")
986 parser.add_argument("--show-output", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000987 parser.add_argument("--cpu",
988 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000989 parser.add_argument("--tfa", action="store_true")
Saul Romero42a13632022-12-20 15:13:36 +0000990 parser.add_argument("--coverage_plugin", default="")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100991 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100992
J-Alves8cc7dbb2021-04-16 10:38:48 +0100993 # Create class which will manage all test artifacts.
994 if args.hypervisor and args.spmc:
995 test_set_up = "hypervisor_and_spmc"
996 elif args.hypervisor:
997 test_set_up = "hypervisor"
998 elif args.spmc:
999 test_set_up = "spmc"
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001000 elif args.el3_spmc:
1001 test_set_up = "el3_spmc"
J-Alves8cc7dbb2021-04-16 10:38:48 +01001002 else:
1003 raise Exception("No Hafnium image provided!\n")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001004
J-Alves8cc7dbb2021-04-16 10:38:48 +01001005 initrd = None
1006 if args.hypervisor and args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +01001007 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
1008 initrd = os.path.join(initrd_dir, "initrd.img")
J-Alves8cc7dbb2021-04-16 10:38:48 +01001009 test_set_up += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +00001010 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +01001011
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001012 partitions = None
J-Alves18a25f92021-05-04 17:47:41 +01001013 global_run_name = None
1014 if args.driver == "fvp":
1015 if args.partitions_json is not None:
1016 partitions_dir = os.path.join(
1017 args.out_partitions, "obj", args.partitions_json)
1018 partitions = json.load(open(partitions_dir, "r"))
1019 global_run_name = os.path.basename(args.partitions_json).split(".")[0]
1020 elif args.hypervisor:
1021 if args.initrd:
1022 global_run_name = os.path.basename(args.initrd)
1023 else:
1024 global_run_name = os.path.basename(args.hypervisor).split(".")[0]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001025
David Brazdil2df24082019-09-05 11:55:08 +01001026 # Create class which will manage all test artifacts.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001027 log_dir = os.path.join(args.log, test_set_up)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001028 artifacts = ArtifactsManager(log_dir)
David Brazdil2df24082019-09-05 11:55:08 +01001029
1030 # Create a driver for the platform we want to test on.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001031 driver_args = DriverArgs(artifacts, args.hypervisor, args.spmc, initrd,
Saul Romero42a13632022-12-20 15:13:36 +00001032 vm_args, args.cpu, partitions, global_run_name,
1033 args.coverage_plugin)
David Brazdil17e76652020-01-29 14:44:19 +00001034
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001035 if args.el3_spmc:
J-Alves38223dd2021-04-20 17:31:48 +01001036 # So far only FVP supports tests for SPMC.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001037 if args.driver != "fvp":
1038 raise Exception("Secure tests can only run with fvp driver")
Shruti Gupta22dbef32023-04-03 10:26:31 +01001039 if args.hypervisor:
1040 driver = FvpDriverEL3SPMCBothWorlds(driver_args)
1041 else:
1042 driver = FvpDriverEL3SPMC(driver_args)
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001043 elif args.spmc:
1044 # So far only FVP supports tests for SPMC.
1045 if args.driver != "fvp":
1046 raise Exception("Secure tests can only run with fvp driver")
J-Alves38223dd2021-04-20 17:31:48 +01001047 if args.hypervisor:
1048 driver = FvpDriverBothWorlds(driver_args)
1049 else:
1050 driver = FvpDriverSPMC(driver_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +01001051 elif args.hypervisor:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001052 if args.driver == "qemu":
J-Alves8cc7dbb2021-04-16 10:38:48 +01001053 out = os.path.dirname(args.hypervisor)
1054 driver = QemuDriver(driver_args, out, args.tfa)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001055 elif args.driver == "fvp":
1056 driver = FvpDriverHypervisor(driver_args)
1057 elif args.driver == "serial":
1058 driver = SerialDriver(driver_args, args.serial_dev,
1059 args.serial_baudrate, not args.serial_no_init_wait)
1060 else:
1061 raise Exception("Unknown driver name: {}".format(args.driver))
J-Alves8cc7dbb2021-04-16 10:38:48 +01001062 else:
1063 raise Exception("No Hafnium image provided!\n")
David Brazdil2df24082019-09-05 11:55:08 +01001064
1065 # Create class which will drive test execution.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001066 runner = TestRunner(artifacts, driver, test_set_up, args.suite, args.test,
J-Alves67c31912023-02-02 13:52:50 +00001067 args.skip_long_running_tests, args.force_long_running, args.debug, args.show_output)
David Brazdil2df24082019-09-05 11:55:08 +01001068
1069 # Run tests.
1070 runner_result = runner.run_tests()
1071
1072 # Print error message if no tests were run as this is probably unexpected.
1073 # Return suitable error code.
1074 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001075 print("Error: no tests match")
1076 return 10
David Brazdil2df24082019-09-05 11:55:08 +01001077 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001078 return 1
1079 else:
David Brazdil2df24082019-09-05 11:55:08 +01001080 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +01001081
1082if __name__ == "__main__":
1083 sys.exit(Main())