blob: b63e8022874f4f320a92fa6f205b4af646a133ee [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
Karl Meakin6f1f1212024-07-16 10:18:16 +010044HFTEST_CTRL_JSON_REGEX = re.compile("^(VM|SP)0x[0-9a-fA-F]+@0x[0-9a-fA-F]+: ")
45
David Brazdil2df24082019-09-05 11:55:08 +010046HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
47 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010048DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010049FVP_BINARY = os.path.join(
Olivier Deprez9f4bad42021-06-18 12:19:07 +020050 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMvA_pkg", "models",
Olivier Deprez78d94eb2023-01-31 09:02:32 +000051 "Linux64_armv8l_GCC-9.3" if MACHINE == "aarch64" else "Linux64_GCC-9.3",
52 "FVP_Base_RevC-2xAEMvA")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010053HF_PREBUILTS = os.path.join(HF_ROOT, "prebuilts")
Olivier Deprez78d94eb2023-01-31 09:02:32 +000054QEMU_PREBUILTS = os.path.join(HF_PREBUILTS,
55 "linux-" + ("x64" if MACHINE == "x86_64" else MACHINE),
56 "qemu", "qemu-system-aarch64")
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010057FVP_PREBUILTS_TFA_ROOT = os.path.join(
58 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010059FVP_PREBUILT_DTS = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010060 FVP_PREBUILTS_TFA_ROOT, "fvp-base-gicv3-psci-1t.dts")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010061
Olivier Deprez1b1c4b62023-01-17 09:56:32 +010062FVP_PREBUILT_TFA_SPMD_ROOT = os.path.join(
63 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-spmd", "fvp")
Andrew Scull845fc9b2019-04-03 12:44:26 +010064
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +000065FVP_PREBUILTS_TFA_EL3_SPMC_ROOT = os.path.join(
66 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-el3-spmc")
J-Alves852fe742021-04-22 11:59:55 +010067VM_NODE_REGEX = "vm[1-9]"
68
Olivier Deprez3917deb2023-01-19 11:08:43 +010069QEMU_CPU_MAX = "max,pauth-impdef=true"
70
David Brazdil2df24082019-09-05 11:55:08 +010071def read_file(path):
72 with open(path, "r") as f:
73 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010074
David Brazdil2df24082019-09-05 11:55:08 +010075def write_file(path, to_write, append=False):
76 with open(path, "a" if append else "w") as f:
77 f.write(to_write)
78
79def append_file(path, to_write):
80 write_file(path, to_write, append=True)
81
82def join_if_not_None(*args):
83 return " ".join(filter(lambda x: x, args))
84
J-Alves852fe742021-04-22 11:59:55 +010085def get_vm_node_from_manifest(dts : str):
86 """ Get VM node string from Partition's extension to Partition Manager's
87 manifest."""
88 match = re.search(VM_NODE_REGEX, dts)
89 if not match:
90 raise Exception("Partition's node is not defined in its manifest.")
91 return match.group()
92
93def correct_vm_node(dts: str, node_index : int):
94 """ The vm node is being appended to the Partition Manager manifests.
95 Ideally, these files would be reused accross various test set-ups."""
96 return dts.replace(get_vm_node_from_manifest(dts), f"vm{node_index}")
97
J-Alves8cc7dbb2021-04-16 10:38:48 +010098DT = collections.namedtuple("DT", ["dts", "dtb"])
99
David Brazdil2df24082019-09-05 11:55:08 +0100100class ArtifactsManager:
101 """Class which manages folder with test artifacts."""
102
103 def __init__(self, log_dir):
104 self.created_files = []
105 self.log_dir = log_dir
106
107 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +0100108 try:
David Brazdil2df24082019-09-05 11:55:08 +0100109 os.makedirs(self.log_dir)
110 except OSError:
111 if not os.path.isdir(self.log_dir):
112 raise
113 print("Logs saved under", log_dir)
114
115 # Create files expected by the Sponge test result parser.
116 self.sponge_log_path = self.create_file("sponge_log", ".log")
117 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
118
David Brazdil623b6812019-09-09 11:41:08 +0100119 def gen_file_path(self, basename, extension):
120 """Generate path to a file in the log directory."""
121 return os.path.join(self.log_dir, basename + extension)
122
David Brazdil2df24082019-09-05 11:55:08 +0100123 def create_file(self, basename, extension):
124 """Create and touch a new file in the log folder. Ensure that no other
125 file of the same name was created by this instance of ArtifactsManager.
126 """
127 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +0100128 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +0100129
130 # Check that the path is unique.
131 assert(path not in self.created_files)
132 self.created_files += [ path ]
133
134 # Touch file.
135 with open(path, "w") as f:
136 pass
137
138 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100139
David Brazdil623b6812019-09-09 11:41:08 +0100140 def get_file(self, basename, extension):
141 """Return path to a file in the log folder. Assert that it was created
142 by this instance of ArtifactsManager."""
143 path = self.gen_file_path(basename, extension)
144 assert(path in self.created_files)
145 return path
146
Andrew Scullbc7189d2018-08-14 09:35:13 +0100147
David Brazdil2df24082019-09-05 11:55:08 +0100148# Tuple holding the arguments common to all driver constructors.
149# This is to avoid having to pass arguments from subclasses to superclasses.
150DriverArgs = collections.namedtuple("DriverArgs", [
151 "artifacts",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100152 "hypervisor",
153 "spmc",
David Brazdil2df24082019-09-05 11:55:08 +0100154 "initrd",
155 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000156 "cpu",
J-Alves18a25f92021-05-04 17:47:41 +0100157 "partitions",
158 "global_run_name",
Saul Romero42a13632022-12-20 15:13:36 +0000159 "coverage_plugin",
David Brazdil2df24082019-09-05 11:55:08 +0100160 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100161
David Brazdil2df24082019-09-05 11:55:08 +0100162# State shared between the common Driver class and its subclasses during
163# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100164class DriverRunState:
165 def __init__(self, log_path):
166 self.log_path = log_path
167 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000168
David Brazdil7325eaf2019-09-27 13:04:51 +0100169 def set_ret_code(self, ret_code):
170 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000171
David Brazdil0dbb41f2019-09-09 18:03:35 +0100172class DriverRunException(Exception):
173 """Exception thrown if subprocess invoked by a driver returned non-zero
174 status code. Used to fast-exit from a driver command sequence."""
175 pass
176
177
David Brazdil2df24082019-09-05 11:55:08 +0100178class Driver:
179 """Parent class of drivers for all testable platforms."""
180
181 def __init__(self, args):
182 self.args = args
183
David Brazdil623b6812019-09-09 11:41:08 +0100184 def get_run_log(self, run_name):
185 """Return path to the main log of a given test run."""
186 return self.args.artifacts.get_file(run_name, ".log")
187
David Brazdil2df24082019-09-05 11:55:08 +0100188 def start_run(self, run_name):
189 """Hook called by Driver subclasses before they invoke the target
190 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100191 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100192
Andrew Walbranf636b842020-01-10 11:46:12 +0000193 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100194 """Run a subprocess on behalf of a Driver subclass and append its
195 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100196 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100197 with open(run_state.log_path, "a") as f:
198 f.write("$ {}\r\n".format(" ".join(exec_args)))
199 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000200 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100201 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100202 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100203 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100204
David Brazdil0dbb41f2019-09-09 18:03:35 +0100205 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100206 """Hook called by Driver subclasses after they finished running the
207 target platform. `ret_code` argument is the return code of the main
208 command run by the driver. A corresponding log message is printed."""
209 # Decode return code and add a message to the log.
210 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100211 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100212 f.write("\r\n{}{} timed out\r\n".format(
213 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100214 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100215 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100216 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
217 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100218
219 # Append log of this run to full test log.
220 log_content = read_file(run_state.log_path)
221 append_file(
222 self.args.artifacts.sponge_log_path,
223 log_content + "\r\n\r\n")
224 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000225
David Brazdil2df24082019-09-05 11:55:08 +0100226class QemuDriver(Driver):
227 """Driver which runs tests in QEMU."""
228
Andrew Walbranf636b842020-01-10 11:46:12 +0000229 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100230 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000231 self.qemu_wd = qemu_wd
232 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100233
David Brazdila2358d42020-01-27 18:51:38 +0000234 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100235 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100236 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000237 # If no CPU configuration is selected, then test against the maximum
238 # configuration, "max", supported by QEMU.
Olivier Deprez3917deb2023-01-19 11:08:43 +0100239 if not self.args.cpu or self.args.cpu == "max":
240 cpu = QEMU_CPU_MAX
241 else:
242 cpu = self.args.cpu
243
David Brazdil2df24082019-09-05 11:55:08 +0100244 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100245 "timeout", "--foreground", time_limit,
Olivier Depreze30c36f2022-11-22 11:26:47 +0100246 QEMU_PREBUILTS,
Olivier Deprez5373f232022-11-23 09:57:19 +0100247 "-no-reboot", "-machine", "virt-6.2,virtualization=on,gic-version=3",
J-Alves871e3732022-05-31 17:10:50 +0100248 "-cpu", cpu, "-smp", "8", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100249 "-nographic", "-nodefaults", "-serial", "stdio",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100250 "-d", "unimp", "-kernel", os.path.abspath(self.args.hypervisor),
David Brazdil2df24082019-09-05 11:55:08 +0100251 ]
252
Andrew Walbranf636b842020-01-10 11:46:12 +0000253 if self.tfa:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100254 bl1_path = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +0100255 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100256 "qemu", "bl1.bin")
Andrew Walbranf636b842020-01-10 11:46:12 +0000257 exec_args += ["-bios",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100258 os.path.abspath(bl1_path),
259 "-machine", "secure=on", "-semihosting-config",
Andrew Walbranab4b2d52020-06-11 16:54:10 +0100260 "enable=on,target=native"]
Andrew Walbranf636b842020-01-10 11:46:12 +0000261
David Brazdil2df24082019-09-05 11:55:08 +0100262 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000263 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100264
265 vm_args = join_if_not_None(self.args.vm_args, test_args)
266 if vm_args:
267 exec_args += ["-append", vm_args]
268
269 return exec_args
270
J-Alves67c31912023-02-02 13:52:50 +0000271 def run(self, run_name, test_args, is_long_running, debug = False,
272 show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100273 """Run test given by `test_args` in QEMU."""
J-Alves67c31912023-02-02 13:52:50 +0000274 # TODO: use 'debug' and 'show_output' flags.
David Brazdil2df24082019-09-05 11:55:08 +0100275 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100276
277 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100278 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000279 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000280 self.exec_logged(run_state, exec_args,
281 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100282 except DriverRunException:
283 pass
284
285 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100286
David Brazdil94fd1e92020-02-03 16:45:20 +0000287 def finish(self):
288 """Clean up after running tests."""
289 pass
290
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100291class FvpDriver(Driver, ABC):
292 """Base class for driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100293
J-Alves19216692023-05-12 15:01:31 +0100294 def __init__(self, args, cpu_start_address, fvp_prebuilt_bl31):
Saul Romero42a13632022-12-20 15:13:36 +0000295 self.cov_plugin = args.coverage_plugin or None
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000296 if args.cpu:
297 raise ValueError("FVP emulator does not support the --cpu option.")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100298 super().__init__(args)
J-Alves19216692023-05-12 15:01:31 +0100299 self._cpu_start_address = cpu_start_address
300 self._fvp_prebuilt_bl31 = fvp_prebuilt_bl31
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100301
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100302 def create_dt(self, run_name : str):
303 """Create DT related files, and return respective paths in a tuple
304 (dts,dtb)"""
J-Alves8cc7dbb2021-04-16 10:38:48 +0100305 return DT(self.args.artifacts.create_file(run_name, ".dts"),
306 self.args.artifacts.create_file(run_name, ".dtb"))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100307
J-Alves8cc7dbb2021-04-16 10:38:48 +0100308 def compile_dt(self, run_state, dt : DT):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100309 """Compile DT calling dtc."""
310 dtc_args = [
J-Alves8cc7dbb2021-04-16 10:38:48 +0100311 DTC_SCRIPT, "compile", "-i", dt.dts, "-o", dt.dtb,
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100312 ]
313 self.exec_logged(run_state, dtc_args)
314
315 def create_uart_log(self, run_name : str, file_name : str):
316 """Create uart log file, and return path"""
317 return self.args.artifacts.create_file(run_name, file_name)
318
319 def get_img_and_ldadd(self, partitions : dict):
320 ret = []
321 for i, p in enumerate(partitions):
J-Alves852fe742021-04-22 11:59:55 +0100322 with open(p["dts"], "r") as dt:
323 dts = dt.read()
324 manifest = fdt.parse_dts(dts)
325 vm_node = get_vm_node_from_manifest(dts)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100326 load_address = manifest.get_property("load_address",
J-Alves852fe742021-04-22 11:59:55 +0100327 f"/hypervisor/{vm_node}").value
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100328 ret.append((p["img"], load_address))
329 return ret
330
331 def get_manifests_from_json(self, partitions : list):
332 manifests = ""
333 if partitions is not None:
J-Alves852fe742021-04-22 11:59:55 +0100334 for i, p in enumerate(partitions):
335 manifests += correct_vm_node(read_file(p["dts"]), i + 1)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100336 return manifests
337
338 @abstractmethod
J-Alves8cc7dbb2021-04-16 10:38:48 +0100339 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100340 """Abstract method to generate dts file. This specific to the use case
341 so should be implemented within derived driver"""
342 pass
343
344 @abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +0100345 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000346 self, is_long_running, uart0_log_path, uart1_log_path, dt,
347 debug = False, show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100348 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000349 show_output = debug or show_output
Madhukar Pappireddycc544be2023-10-18 15:01:58 -0500350 time_limit = "100s" if is_long_running else "40s"
J-Alves67c31912023-02-02 13:52:50 +0000351 fvp_args = []
352
353 if not show_output:
354 fvp_args = [
355 "timeout", "--foreground", time_limit,
356 ]
357
358 fvp_args += [
David Brazdil2df24082019-09-05 11:55:08 +0100359 FVP_BINARY,
J-Alves10446d82021-04-26 11:52:57 +0100360 "-C", "pci.pci_smmuv3.mmu.SMMU_AIDR=2",
361 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR0=0x0046123B",
362 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR1=0x00600002",
363 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR3=0x1714",
364 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR5=0xFFFF0472",
365 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR1=0xA0000002",
366 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR2=0",
367 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR3=0",
David Brazdil2df24082019-09-05 11:55:08 +0100368 "-C", "pctl.startup=0.0.0.0",
Olivier Deprezcd857002022-05-09 09:06:24 +0200369 "-C", "bp.secure_memory=1",
David Brazdil2df24082019-09-05 11:55:08 +0100370 "-C", "cluster0.NUM_CORES=4",
371 "-C", "cluster1.NUM_CORES=4",
372 "-C", "cache_state_modelled=0",
David Brazdil2df24082019-09-05 11:55:08 +0100373 "-C", "bp.vis.rate_limit-enable=false",
David Brazdil2df24082019-09-05 11:55:08 +0100374 "-C", "bp.pl011_uart0.untimed_fifos=1",
375 "-C", "bp.pl011_uart0.unbuffered_output=1",
J-Alves19216692023-05-12 15:01:31 +0100376 "-C", f"cluster0.cpu0.RVBAR={self._cpu_start_address}",
377 "-C", f"cluster0.cpu1.RVBAR={self._cpu_start_address}",
378 "-C", f"cluster0.cpu2.RVBAR={self._cpu_start_address}",
379 "-C", f"cluster0.cpu3.RVBAR={self._cpu_start_address}",
380 "-C", f"cluster1.cpu0.RVBAR={self._cpu_start_address}",
381 "-C", f"cluster1.cpu1.RVBAR={self._cpu_start_address}",
382 "-C", f"cluster1.cpu2.RVBAR={self._cpu_start_address}",
383 "-C", f"cluster1.cpu3.RVBAR={self._cpu_start_address}",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100384 "--data",
J-Alves19216692023-05-12 15:01:31 +0100385 f"cluster0.cpu0={self._fvp_prebuilt_bl31}@{self._cpu_start_address}",
David Brazdil2df24082019-09-05 11:55:08 +0100386 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
Raghu Krishnamurthy75ebf8c2021-11-28 07:22:12 -0800387 "-C", "cluster0.has_arm_v8-5=1",
388 "-C", "cluster1.has_arm_v8-5=1",
389 "-C", "cluster0.has_branch_target_exception=1",
390 "-C", "cluster1.has_branch_target_exception=1",
Maksims Svecovsce1261f2022-03-04 15:22:58 +0000391 "-C", "cluster0.memory_tagging_support_level=2",
392 "-C", "cluster1.memory_tagging_support_level=2",
393 "-C", "bp.dram_metadata.is_enabled=1",
Raghu Krishnamurthye2eae292022-08-10 22:38:41 -0700394 "-C", "cluster0.gicv3.extended-interrupt-range-support=1",
395 "-C", "cluster1.gicv3.extended-interrupt-range-support=1",
396 "-C", "gic_distributor.extended-ppi-count=64",
397 "-C", "gic_distributor.extended-spi-count=1024",
398 "-C", "gic_distributor.ARE-fixed-to-one=1",
David Brazdil2df24082019-09-05 11:55:08 +0100399 ]
J-Alves18a25f92021-05-04 17:47:41 +0100400
401 if uart0_log_path and uart1_log_path:
402 fvp_args += [
403 "-C", f"bp.pl011_uart0.out_file={uart0_log_path}",
404 "-C", f"bp.pl011_uart1.out_file={uart1_log_path}",
405 ]
J-Alves67c31912023-02-02 13:52:50 +0000406
407 if not show_output:
408 fvp_args += [
409 "-C", "bp.vis.disable_visualisation=true",
410 "-C", "bp.terminal_0.start_telnet=false",
411 "-C", "bp.terminal_1.start_telnet=false",
412 "-C", "bp.terminal_2.start_telnet=false",
413 "-C", "bp.terminal_3.start_telnet=false",
414 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
415 ]
416
417 if debug:
418 fvp_args += [
Saul Romero42a13632022-12-20 15:13:36 +0000419 "-I", "-p"
420 ]
421
422 if self.cov_plugin is not None:
423 fvp_args += [
424 "--plugin", self.cov_plugin
J-Alves67c31912023-02-02 13:52:50 +0000425 ]
David Brazdil2df24082019-09-05 11:55:08 +0100426 return fvp_args
427
J-Alves67c31912023-02-02 13:52:50 +0000428 def run(self, run_name, test_args, is_long_running, debug = False,
429 show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100430 """ Run test """
David Brazdil2df24082019-09-05 11:55:08 +0100431 run_state = self.start_run(run_name)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100432 dt = self.create_dt(run_name)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100433 uart0_log_path = self.create_uart_log(run_name, ".uart0.log")
434 uart1_log_path = self.create_uart_log(run_name, ".uart1.log")
David Brazdil2df24082019-09-05 11:55:08 +0100435
David Brazdil0dbb41f2019-09-09 18:03:35 +0100436 try:
J-Alves8cc7dbb2021-04-16 10:38:48 +0100437 self.gen_dts(dt, test_args)
438 self.compile_dt(run_state, dt)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100439 fvp_args = self.gen_fvp_args(is_long_running, uart0_log_path,
J-Alves67c31912023-02-02 13:52:50 +0000440 uart1_log_path, dt, debug=debug,
441 show_output=show_output)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100442 self.exec_logged(run_state, fvp_args)
443 except DriverRunException:
444 pass
David Brazdil2df24082019-09-05 11:55:08 +0100445
446 # Append UART0 output to main log.
447 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100448 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100449
David Brazdil94fd1e92020-02-03 16:45:20 +0000450 def finish(self):
451 """Clean up after running tests."""
452 pass
453
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100454class FvpDriverHypervisor(FvpDriver):
455 """
456 Driver which runs tests in Arm FVP emulator, with hafnium as hypervisor
457 """
458 INITRD_START= 0x84000000
Olivier Depreza516f482021-04-30 18:47:59 +0200459 INITRD_END = 0x86000000 #Default value, however may change if initrd in args
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100460
J-Alves19216692023-05-12 15:01:31 +0100461 def __init__(self, args, hypervisor_address=0x80000000, hypervisor_dtb_address=0x82000000):
462 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILTS_TFA_ROOT, "bl31.bin")
463 FvpDriver.__init__(self, args, 0x04020000, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100464 self.vms_in_partitions_json = args.partitions and args.partitions["VMs"]
J-Alves19216692023-05-12 15:01:31 +0100465 self._hypervisor_address = hypervisor_address
466 self._hypervisor_dtb_address = hypervisor_dtb_address
J-Alves38223dd2021-04-20 17:31:48 +0100467
J-Alves8cc7dbb2021-04-16 10:38:48 +0100468 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100469 """Create a DeviceTree source which will be compiled into a DTB and
470 passed to FVP for a test run."""
471
472 vm_args = join_if_not_None(self.args.vm_args, test_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100473 write_file(dt.dts, read_file(FVP_PREBUILT_DTS))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100474
475 # Write the vm arguments to the partition manifest
476 to_append = f"""
477/ {{
478 chosen {{
479 bootargs = "{vm_args}";
480 stdout-path = "serial0:115200n8";
481 linux,initrd-start = <{self.INITRD_START if self.args.initrd else 0}>;
482 linux,initrd-end = <{self.INITRD_END if self.args.initrd else 0}>;
483 }};
484}};"""
485 if self.vms_in_partitions_json:
486 to_append += self.get_manifests_from_json(self.args.partitions["VMs"])
487
J-Alves8cc7dbb2021-04-16 10:38:48 +0100488 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100489
490 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000491 self, is_long_running, uart0_log_path, uart1_log_path, dt,
492 debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100493 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000494 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt,
495 debug, show_output)
496 fvp_args = FvpDriver.gen_fvp_args(*common_args)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100497
J-Alves8cc7dbb2021-04-16 10:38:48 +0100498 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100499 "--data", f"cluster0.cpu0={dt.dtb}@{self._hypervisor_dtb_address}",
500 "--data", f"cluster0.cpu0={self.args.hypervisor}@{self._hypervisor_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100501 ]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100502
503 if self.vms_in_partitions_json:
504 img_ldadd = self.get_img_and_ldadd(self.args.partitions["VMs"])
505 for img, ldadd in img_ldadd:
506 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
507
508 if self.args.initrd:
509 fvp_args += [
510 "--data",
511 f"cluster0.cpu0={self.args.initrd}@{self.INITRD_START}"
512 ]
513 return fvp_args
514
515class FvpDriverSPMC(FvpDriver):
516 """
517 Driver which runs tests in Arm FVP emulator, with hafnium as SPMC
518 """
519 FVP_PREBUILT_SECURE_DTS = os.path.join(
520 HF_ROOT, "test", "vmapi", "fvp-base-spmc.dts")
J-Alvesacdbb862023-01-31 17:14:55 +0000521 hftest_cmd_file = tempfile.NamedTemporaryFile(mode="w+")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100522
J-Alves19216692023-05-12 15:01:31 +0100523 def __init__(self, args, cpu_start_address=0x04010000, fvp_prebuilt_bl31=None):
524 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILT_TFA_SPMD_ROOT, "bl31.bin") if fvp_prebuilt_bl31 is None else fvp_prebuilt_bl31
525 super().__init__(args, cpu_start_address, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100526
J-Alves19216692023-05-12 15:01:31 +0100527 self._spmc_address = 0x6000000
528 self._spmc_dtb_address = 0x0403f000
J-Alves38223dd2021-04-20 17:31:48 +0100529
J-Alves8cc7dbb2021-04-16 10:38:48 +0100530 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100531 """Create a DeviceTree source which will be compiled into a DTB and
532 passed to FVP for a test run."""
533 to_append = self.get_manifests_from_json(self.args.partitions["SPs"])
J-Alves8cc7dbb2021-04-16 10:38:48 +0100534 write_file(dt.dts, read_file(FvpDriverSPMC.FVP_PREBUILT_SECURE_DTS))
535 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100536
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000537 def secure_ctrl_fvp_args(self, secure_ctrl):
538 fvp_args = ""
539 if secure_ctrl:
540 fvp_args = [
541 "-C", f"bp.pl011_uart0.in_file={FvpDriverSPMC.hftest_cmd_file.name}",
542 "-C", f"bp.pl011_uart0.shutdown_tag=\"{HFTEST_CTRL_FINISHED}\"",
543 ]
544 return fvp_args
545
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100546 def gen_fvp_args(
J-Alves8cc7dbb2021-04-16 10:38:48 +0100547 self, is_long_running, uart0_log_path, uart1_log_path, dt,
J-Alves67c31912023-02-02 13:52:50 +0000548 call_super = True, secure_ctrl = True, debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100549 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000550 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
551 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100552 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
J-Alves8cc7dbb2021-04-16 10:38:48 +0100553
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100554 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100555 "--data", f"cluster0.cpu0={dt.dtb}@{self._spmc_dtb_address}",
556 "--data", f"cluster0.cpu0={self.args.spmc}@{self._spmc_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100557 ]
558
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000559 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
J-Alves18a25f92021-05-04 17:47:41 +0100560
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100561 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
562 for img, ldadd in img_ldadd:
563 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
564
565 return fvp_args
566
J-Alves67c31912023-02-02 13:52:50 +0000567 def run(self, run_name, test_args, is_long_running, debug = False, show_output = False):
J-Alvesacdbb862023-01-31 17:14:55 +0000568 vm_args = join_if_not_None(self.args.vm_args, test_args)
569 FvpDriverSPMC.hftest_cmd_file.write(f"{vm_args}\n")
570 FvpDriverSPMC.hftest_cmd_file.seek(0)
J-Alves67c31912023-02-02 13:52:50 +0000571 return super().run(run_name, test_args, is_long_running, debug, show_output)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100572
573 def finish(self):
574 """Clean up after running tests."""
J-Alvesacdbb862023-01-31 17:14:55 +0000575 FvpDriverSPMC.hftest_cmd_file.close()
David Brazdil2df24082019-09-05 11:55:08 +0100576
J-Alves38223dd2021-04-20 17:31:48 +0100577class FvpDriverBothWorlds(FvpDriverHypervisor, FvpDriverSPMC):
578 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100579 FvpDriverHypervisor.__init__(self, args, hypervisor_address=0x88000000)
J-Alves38223dd2021-04-20 17:31:48 +0100580 FvpDriverSPMC.__init__(self, args)
581
J-Alves38223dd2021-04-20 17:31:48 +0100582 def create_dt(self, run_name):
583 dt = dict()
584 dt["hypervisor"] = FvpDriver.create_dt(self, run_name + "_hypervisor")
585 dt["spmc"] = FvpDriver.create_dt(self, run_name + "_spmc")
586 return dt
587
J-Alves38223dd2021-04-20 17:31:48 +0100588 def compile_dt(self, run_state, dt):
589 FvpDriver.compile_dt(self, run_state, dt["hypervisor"])
590 FvpDriver.compile_dt(self, run_state, dt["spmc"])
591
592 def gen_dts(self, dt, test_args):
593 FvpDriverHypervisor.gen_dts(self, dt["hypervisor"], test_args)
594 FvpDriverSPMC.gen_dts(self, dt["spmc"], test_args)
595
J-Alves67c31912023-02-02 13:52:50 +0000596 def gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
597 debug = False, show_output = False):
J-Alves38223dd2021-04-20 17:31:48 +0100598 """Generate command line arguments for FVP."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000599 common_args = (self, is_long_running, uart0_log_path, uart1_log_path)
J-Alves67c31912023-02-02 13:52:50 +0000600 fvp_args = FvpDriverHypervisor.gen_fvp_args(*common_args, dt["hypervisor"],
601 debug, show_output)
J-Alves18a25f92021-05-04 17:47:41 +0100602 fvp_args += FvpDriverSPMC.gen_fvp_args(*common_args, dt["spmc"], False,
603 False)
J-Alves8d9fbb92021-12-13 17:28:15 +0000604 return fvp_args
J-Alves18a25f92021-05-04 17:47:41 +0100605
J-Alves67c31912023-02-02 13:52:50 +0000606 def run(self, run_name, test_args, is_long_running, debug = False,
607 show_output = False):
608
609 return FvpDriver.run(self, run_name, test_args, is_long_running,
610 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100611
612 def finish(self):
613 """Clean up after running tests."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000614 FvpDriver.finish(self)
J-Alves38223dd2021-04-20 17:31:48 +0100615
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000616class FvpDriverEL3SPMC(FvpDriverSPMC):
617 """
618 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
619 """
620
621 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100622 FvpDriverSPMC.__init__(
623 self, args, cpu_start_address=0x04003000,
624 fvp_prebuilt_bl31=os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl31.bin"))
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000625 self.vms_in_partitions_json = args.partitions and args.partitions["SPs"]
J-Alves19216692023-05-12 15:01:31 +0100626 self._sp_dtb_address = 0x0403f000
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000627
628 def sp_partition_manifest_fvp_args(self):
629 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
630
631 # Expect only one tuple with img and load address, as EL3 SPMC only supports
632 # one SP.
633 assert(len(img_ldadd) == 1)
634 img, ldadd = img_ldadd[0]
635 fvp_args = ["--data", f"cluster0.cpu0={img}@{ldadd}"]
636
637 # Even though FF-A manifest is part of the SP PKG we need to load at a specific
638 # location. Fetch the respective dtb file and load at the following address.
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000639 output_path = os.path.dirname(os.path.dirname(img))
640 partition_manifest = f"{output_path}/partition-manifest.dtb"
J-Alves19216692023-05-12 15:01:31 +0100641 fvp_args += ["--data", f"cluster0.cpu0={partition_manifest}@{self._sp_dtb_address}"]
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000642 return fvp_args
643
644 def gen_fvp_args(
645 self, is_long_running, uart0_log_path, uart1_log_path, dt,
646 call_super = True, secure_ctrl = True, debug = False, show_output = False):
647 """Generate command line arguments for FVP."""
648 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
649 debug, show_output)
650 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
651
652 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
653
654 fvp_args += self.sp_partition_manifest_fvp_args()
655
656 return fvp_args
657
Shruti Gupta22dbef32023-04-03 10:26:31 +0100658class FvpDriverEL3SPMCBothWorlds(FvpDriverHypervisor, FvpDriverEL3SPMC):
659 """
660 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
661 """
662
J-Alves19216692023-05-12 15:01:31 +0100663 def __init__(self, args):
664 FvpDriverHypervisor.__init__(self, args)
665 FvpDriverEL3SPMC.__init__(self, args)
Shruti Gupta22dbef32023-04-03 10:26:31 +0100666
J-Alves19216692023-05-12 15:01:31 +0100667 self._fvp_prebuilt_bl32 = os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl32.bin")
668 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 +0100669
670 def gen_fvp_args(
671 self, is_long_running, uart0_log_path, uart1_log_path, dt,
672 call_super = True, secure_ctrl = True, debug = False, show_output = False):
673 """Generate command line arguments for FVP."""
674
675 fvp_args = FvpDriverHypervisor.gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
676 debug, show_output)
677
678 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
679
680 if self.args.partitions is not None and self.args.partitions["SPs"] is not None:
681 fvp_args += FvpDriverEL3SPMC.sp_partition_manifest_fvp_args(self)
682 else :
683 # Use prebuilt TSP and TSP manifest if build does not specify SP
684 # EL3 SPMC expects SP to be loaded at 0xFF200000 and SP manifest at 0x0403F000
J-Alves19216692023-05-12 15:01:31 +0100685 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_bl32}@0xff200000"]
686 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_dtb}@{self._sp_dtb_address}"]
Shruti Gupta22dbef32023-04-03 10:26:31 +0100687
688 return fvp_args
689
David Brazdil17e76652020-01-29 14:44:19 +0000690class SerialDriver(Driver):
691 """Driver which communicates with a device over the serial port."""
692
David Brazdil9d4ed962020-02-06 17:23:48 +0000693 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000694 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000695 self.tty_file = tty_file
696 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000697 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000698
David Brazdil9d4ed962020-02-06 17:23:48 +0000699 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000700 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000701
David Brazdil9d4ed962020-02-06 17:23:48 +0000702 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000703 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000704
David Brazdil17e76652020-01-29 14:44:19 +0000705 def run(self, run_name, test_args, is_long_running):
706 """Communicate `test_args` to the device over the serial port."""
707 run_state = self.start_run(run_name)
708
David Brazdil9d4ed962020-02-06 17:23:48 +0000709 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000710 with open(run_state.log_path, "a") as f:
711 while True:
712 # Read one line from the serial port.
713 line = ser.readline().decode('utf-8')
714 if len(line) == 0:
715 # Timeout
716 run_state.set_ret_code(124)
717 input("Timeout. " +
718 "Press ENTER and then reset the device...")
719 break
720 # Write the line to the log file.
721 f.write(line)
722 if HFTEST_CTRL_GET_COMMAND_LINE in line:
723 # Device is waiting for `test_args`.
724 ser.write(test_args.encode('ascii'))
725 ser.write(b'\r')
726 elif HFTEST_CTRL_FINISHED in line:
727 # Device has finished running this test and will reboot.
728 break
J-Alves18a25f92021-05-04 17:47:41 +0100729
David Brazdil17e76652020-01-29 14:44:19 +0000730 return self.finish_run(run_state)
731
David Brazdil94fd1e92020-02-03 16:45:20 +0000732 def finish(self):
733 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000734 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000735 while True:
736 line = ser.readline().decode('utf-8')
737 if len(line) == 0:
738 input("Timeout. Press ENTER and then reset the device...")
739 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
740 # Device is waiting for a command. Instruct it to exit
741 # the test environment.
742 ser.write("exit".encode('ascii'))
743 ser.write(b'\r')
744 break
745
David Brazdil2df24082019-09-05 11:55:08 +0100746# Tuple used to return information about the results of running a set of tests.
747TestRunnerResult = collections.namedtuple("TestRunnerResult", [
748 "tests_run",
749 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100750 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100751 ])
752
David Brazdil2df24082019-09-05 11:55:08 +0100753class TestRunner:
754 """Class which communicates with a test platform to obtain a list of
755 available tests and driving their execution."""
756
J-Alves8cc7dbb2021-04-16 10:38:48 +0100757 def __init__(self, artifacts, driver, test_set_up, suite_regex, test_regex,
J-Alves67c31912023-02-02 13:52:50 +0000758 skip_long_running_tests, force_long_running, debug, show_output):
David Brazdil2df24082019-09-05 11:55:08 +0100759 self.artifacts = artifacts
760 self.driver = driver
J-Alves8cc7dbb2021-04-16 10:38:48 +0100761 self.test_set_up = test_set_up
David Brazdil3cc24aa2019-09-27 10:24:41 +0100762 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100763 self.force_long_running = force_long_running
J-Alves67c31912023-02-02 13:52:50 +0000764 self.debug = debug
765 self.show_output = show_output
David Brazdil2df24082019-09-05 11:55:08 +0100766
767 self.suite_re = re.compile(suite_regex or ".*")
768 self.test_re = re.compile(test_regex or ".*")
769
770 def extract_hftest_lines(self, raw):
771 """Extract hftest-specific lines from a raw output from an invocation
772 of the test platform."""
773 lines = []
J-Alves07be7bb2021-04-13 11:09:12 +0100774 lines_to_process = raw.splitlines()
775
776 try:
777 # If logs have logs of more than one VM, the loop below to extract
778 # lines won't work. Thus, extracting between starting and ending
779 # logs: HFTEST_CTRL_GET_COMMAND_LINE and HFTEST_CTRL_FINISHED.
780 hftest_start = lines_to_process.index(HFTEST_CTRL_GET_COMMAND_LINE) + 1
781 hftest_end = lines_to_process.index(HFTEST_CTRL_FINISHED)
782 except ValueError:
783 hftest_start = 0
784 hftest_end = len(lines_to_process)
785
786 lines_to_process = lines_to_process[hftest_start : hftest_end]
787
788 for line in lines_to_process:
Karl Meakin6f1f1212024-07-16 10:18:16 +0100789 match = HFTEST_CTRL_JSON_REGEX.search(line)
J-Alves3dbb8562020-12-01 10:45:37 +0000790 if match is not None:
791 line = line[match.end():]
David Brazdil2df24082019-09-05 11:55:08 +0100792 if line.startswith(HFTEST_LOG_PREFIX):
793 lines.append(line[len(HFTEST_LOG_PREFIX):])
794 return lines
795
796 def get_test_json(self):
797 """Invoke the test platform and request a JSON of available test and
798 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100799 out = self.driver.run("json", "json", self.force_long_running)
Daniel Boulby61049dc2023-06-16 14:15:21 +0100800 hf_out = self.extract_hftest_lines(out)
Karl Meakinc7a38482024-07-15 10:29:11 +0100801 try:
802 hf_out = hf_out[hf_out.index(HFTEST_CTRL_JSON_START) + 1
Daniel Boulby61049dc2023-06-16 14:15:21 +0100803 :hf_out.index(HFTEST_CTRL_JSON_END)];
Karl Meakinc7a38482024-07-15 10:29:11 +0100804 except ValueError as e:
805 print("Unable to find JSON control string:")
806 print(f"out={out}")
807 print(f"hf_out={hf_out}")
808 raise e
809
Daniel Boulby61049dc2023-06-16 14:15:21 +0100810 hf_out = "\n".join(hf_out)
David Brazdil2df24082019-09-05 11:55:08 +0100811 try:
812 return json.loads(hf_out)
813 except ValueError as e:
Karl Meakinc7a38482024-07-15 10:29:11 +0100814 print("Unable to parse JSON:")
815 print(f"out={out}")
816 print(f"hf_out={hf_outout}")
David Brazdil2df24082019-09-05 11:55:08 +0100817 print(out)
818 raise e
819
820 def collect_results(self, fn, it, xml_node):
821 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
822 Insert "tests" and "failures" nodes to `xml_node`."""
823 tests_run = 0
824 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100825 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100826 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100827 for i in it:
828 sub_result = fn(i)
829 assert(sub_result.tests_run >= sub_result.tests_failed)
830 tests_run += sub_result.tests_run
831 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100832 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100833 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100834
Andrew Walbranf9463922020-06-05 16:44:42 +0100835 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100836 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100837 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100838 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100839 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100840
841 def is_passed_test(self, test_out):
842 """Parse the output of a test and return True if it passed."""
843 return \
844 len(test_out) > 0 and \
845 test_out[-1] == HFTEST_LOG_FINISHED and \
846 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
847
Andrew Walbranf9463922020-06-05 16:44:42 +0100848 def get_failure_message(self, test_out):
849 """Parse the output of a test and return the message of the first
850 assertion failure."""
851 for i, line in enumerate(test_out):
852 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
853 # The assertion message is on the line after the 'Failure:'
854 return test_out[i + 1].strip()
855
856 return None
857
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000858 def get_log_name(self, suite, test):
859 """Returns a string with a generated log name for the test."""
860 log_name = ""
861
862 cpu = self.driver.args.cpu
863 if cpu:
864 log_name += cpu + "."
865
866 log_name += suite["name"] + "." + test["name"]
867
868 return log_name
869
David Brazdil2df24082019-09-05 11:55:08 +0100870 def run_test(self, suite, test, suite_xml):
871 """Invoke the test platform and request to run a given `test` in given
872 `suite`. Create a new XML node with results under `suite_xml`.
873 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100874 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100875 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100876
877 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100878 test_xml.set("name", test["name"])
879 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100880
J-Alvesd459b562022-12-05 14:56:33 +0000881 if (self.skip_long_running_tests and test["is_long_running"]) or test["skip_test"]:
Andrew Walbranf9463922020-06-05 16:44:42 +0100882 print(" SKIP", test["name"])
883 test_xml.set("status", "notrun")
884 skipped_xml = ET.SubElement(test_xml, "skipped")
885 skipped_xml.set("message", "Long running")
886 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
887
J-Alves67c31912023-02-02 13:52:50 +0000888 action_log = "DEBUG" if self.debug else "RUN"
889 print(f" {action_log}", test["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100890 log_name = self.get_log_name(suite, test)
891
David Brazdil2df24082019-09-05 11:55:08 +0100892 test_xml.set("status", "run")
893
Andrew Walbran42bf2842020-06-05 18:50:19 +0100894 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100895 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100896 log_name, "run {} {}".format(suite["name"], test["name"]),
J-Alves67c31912023-02-02 13:52:50 +0000897 test["is_long_running"] or self.force_long_running,
898 self.debug, self.show_output)
899
Andrew Walbranf9463922020-06-05 16:44:42 +0100900 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100901 elapsed_time = time.perf_counter() - start_time
902
903 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100904
Andrew Walbranf9463922020-06-05 16:44:42 +0100905 system_out_xml = ET.SubElement(test_xml, "system-out")
906 system_out_xml.text = out
907
908 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100909 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100910 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100911 else:
David Brazdil623b6812019-09-09 11:41:08 +0100912 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100913 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100914 failure_message = self.get_failure_message(hftest_out) or "Test failed"
915 failure_xml.set("message", failure_message)
916 failure_xml.text = '\n'.join(hftest_out)
917 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100918
919 def run_suite(self, suite, xml):
920 """Invoke the test platform and request to run all matching tests in
921 `suite`. Create new XML nodes with results under `xml`.
922 Suite skipped if it does not match the regex given to constructor."""
923 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100924 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100925
926 print(" SUITE", suite["name"])
927 suite_xml = ET.SubElement(xml, "testsuite")
928 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100929 properties_xml = ET.SubElement(suite_xml, "properties")
930
931 property_xml = ET.SubElement(properties_xml, "property")
932 property_xml.set("name", "driver")
933 property_xml.set("value", type(self.driver).__name__)
934
935 if self.driver.args.cpu:
936 property_xml = ET.SubElement(properties_xml, "property")
937 property_xml.set("name", "cpu")
938 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100939
940 return self.collect_results(
941 lambda test: self.run_test(suite, test, suite_xml),
942 suite["tests"],
943 suite_xml)
944
945 def run_tests(self):
946 """Run all suites and tests matching regexes given to constructor.
947 Write results to sponge log XML. Return the number of run and failed
948 tests."""
949
950 test_spec = self.get_test_json()
951 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
952
953 xml = ET.Element("testsuites")
J-Alves8cc7dbb2021-04-16 10:38:48 +0100954 xml.set("name", self.test_set_up)
David Brazdil2df24082019-09-05 11:55:08 +0100955 xml.set("timestamp", timestamp)
956
957 result = self.collect_results(
958 lambda suite: self.run_suite(suite, xml),
959 test_spec["suites"],
960 xml)
961
962 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000963 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
964 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100965
966 if result.tests_failed > 0:
967 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
968 "tests failed")
969 elif result.tests_run > 0:
970 print(" PASS: all", result.tests_run, "tests passed")
971
David Brazdil94fd1e92020-02-03 16:45:20 +0000972 # Let the driver clean up.
973 self.driver.finish()
974
David Brazdil2df24082019-09-05 11:55:08 +0100975 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100976
Andrew Scullbc7189d2018-08-14 09:35:13 +0100977def Main():
978 parser = argparse.ArgumentParser()
J-Alves8cc7dbb2021-04-16 10:38:48 +0100979 parser.add_argument("--hypervisor")
980 parser.add_argument("--spmc")
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000981 parser.add_argument("--el3_spmc", action="store_true")
Andrew Scull23e93a82018-10-26 14:56:04 +0100982 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100983 parser.add_argument("--out_initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100984 parser.add_argument("--out_partitions")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000985 parser.add_argument("--initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100986 parser.add_argument("--partitions_json")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100987 parser.add_argument("--suite")
988 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000989 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000990 parser.add_argument("--driver", default="qemu")
991 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
992 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000993 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100994 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100995 parser.add_argument("--force-long-running", action="store_true")
J-Alves67c31912023-02-02 13:52:50 +0000996 parser.add_argument("--debug", action="store_true",
997 help="Makes platforms stall waiting for debugger connection.")
998 parser.add_argument("--show-output", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000999 parser.add_argument("--cpu",
1000 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +00001001 parser.add_argument("--tfa", action="store_true")
Saul Romero42a13632022-12-20 15:13:36 +00001002 parser.add_argument("--coverage_plugin", default="")
Andrew Scullbc7189d2018-08-14 09:35:13 +01001003 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +01001004
J-Alves8cc7dbb2021-04-16 10:38:48 +01001005 # Create class which will manage all test artifacts.
1006 if args.hypervisor and args.spmc:
1007 test_set_up = "hypervisor_and_spmc"
1008 elif args.hypervisor:
1009 test_set_up = "hypervisor"
1010 elif args.spmc:
1011 test_set_up = "spmc"
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001012 elif args.el3_spmc:
1013 test_set_up = "el3_spmc"
J-Alves8cc7dbb2021-04-16 10:38:48 +01001014 else:
1015 raise Exception("No Hafnium image provided!\n")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001016
J-Alves8cc7dbb2021-04-16 10:38:48 +01001017 initrd = None
1018 if args.hypervisor and args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +01001019 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
1020 initrd = os.path.join(initrd_dir, "initrd.img")
J-Alves8cc7dbb2021-04-16 10:38:48 +01001021 test_set_up += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +00001022 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +01001023
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001024 partitions = None
J-Alves18a25f92021-05-04 17:47:41 +01001025 global_run_name = None
1026 if args.driver == "fvp":
1027 if args.partitions_json is not None:
1028 partitions_dir = os.path.join(
1029 args.out_partitions, "obj", args.partitions_json)
1030 partitions = json.load(open(partitions_dir, "r"))
1031 global_run_name = os.path.basename(args.partitions_json).split(".")[0]
1032 elif args.hypervisor:
1033 if args.initrd:
1034 global_run_name = os.path.basename(args.initrd)
1035 else:
1036 global_run_name = os.path.basename(args.hypervisor).split(".")[0]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001037
David Brazdil2df24082019-09-05 11:55:08 +01001038 # Create class which will manage all test artifacts.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001039 log_dir = os.path.join(args.log, test_set_up)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001040 artifacts = ArtifactsManager(log_dir)
David Brazdil2df24082019-09-05 11:55:08 +01001041
1042 # Create a driver for the platform we want to test on.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001043 driver_args = DriverArgs(artifacts, args.hypervisor, args.spmc, initrd,
Saul Romero42a13632022-12-20 15:13:36 +00001044 vm_args, args.cpu, partitions, global_run_name,
1045 args.coverage_plugin)
David Brazdil17e76652020-01-29 14:44:19 +00001046
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001047 if args.el3_spmc:
J-Alves38223dd2021-04-20 17:31:48 +01001048 # So far only FVP supports tests for SPMC.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001049 if args.driver != "fvp":
1050 raise Exception("Secure tests can only run with fvp driver")
Shruti Gupta22dbef32023-04-03 10:26:31 +01001051 if args.hypervisor:
1052 driver = FvpDriverEL3SPMCBothWorlds(driver_args)
1053 else:
1054 driver = FvpDriverEL3SPMC(driver_args)
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001055 elif args.spmc:
1056 # So far only FVP supports tests for SPMC.
1057 if args.driver != "fvp":
1058 raise Exception("Secure tests can only run with fvp driver")
J-Alves38223dd2021-04-20 17:31:48 +01001059 if args.hypervisor:
1060 driver = FvpDriverBothWorlds(driver_args)
1061 else:
1062 driver = FvpDriverSPMC(driver_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +01001063 elif args.hypervisor:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001064 if args.driver == "qemu":
J-Alves8cc7dbb2021-04-16 10:38:48 +01001065 out = os.path.dirname(args.hypervisor)
1066 driver = QemuDriver(driver_args, out, args.tfa)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001067 elif args.driver == "fvp":
1068 driver = FvpDriverHypervisor(driver_args)
1069 elif args.driver == "serial":
1070 driver = SerialDriver(driver_args, args.serial_dev,
1071 args.serial_baudrate, not args.serial_no_init_wait)
1072 else:
1073 raise Exception("Unknown driver name: {}".format(args.driver))
J-Alves8cc7dbb2021-04-16 10:38:48 +01001074 else:
1075 raise Exception("No Hafnium image provided!\n")
David Brazdil2df24082019-09-05 11:55:08 +01001076
1077 # Create class which will drive test execution.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001078 runner = TestRunner(artifacts, driver, test_set_up, args.suite, args.test,
J-Alves67c31912023-02-02 13:52:50 +00001079 args.skip_long_running_tests, args.force_long_running, args.debug, args.show_output)
David Brazdil2df24082019-09-05 11:55:08 +01001080
1081 # Run tests.
1082 runner_result = runner.run_tests()
1083
1084 # Print error message if no tests were run as this is probably unexpected.
1085 # Return suitable error code.
1086 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001087 print("Error: no tests match")
1088 return 10
David Brazdil2df24082019-09-05 11:55:08 +01001089 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001090 return 1
1091 else:
David Brazdil2df24082019-09-05 11:55:08 +01001092 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +01001093
1094if __name__ == "__main__":
1095 sys.exit(Main())