blob: 4a44e2f33f29da8d21fbb157c5c78faf1e8dee99 [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
David Brazdil17e76652020-01-29 14:44:19 +000038HFTEST_CTRL_GET_COMMAND_LINE = "[hftest_ctrl:get_command_line]"
39HFTEST_CTRL_FINISHED = "[hftest_ctrl:finished]"
40
David Brazdil2df24082019-09-05 11:55:08 +010041HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
42 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010043DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010044FVP_BINARY = os.path.join(
Olivier Deprez9f4bad42021-06-18 12:19:07 +020045 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMvA_pkg", "models",
Olivier Deprez78d94eb2023-01-31 09:02:32 +000046 "Linux64_armv8l_GCC-9.3" if MACHINE == "aarch64" else "Linux64_GCC-9.3",
47 "FVP_Base_RevC-2xAEMvA")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010048HF_PREBUILTS = os.path.join(HF_ROOT, "prebuilts")
Olivier Deprez78d94eb2023-01-31 09:02:32 +000049QEMU_PREBUILTS = os.path.join(HF_PREBUILTS,
50 "linux-" + ("x64" if MACHINE == "x86_64" else MACHINE),
51 "qemu", "qemu-system-aarch64")
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010052FVP_PREBUILTS_TFA_ROOT = os.path.join(
53 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010054FVP_PREBUILT_DTS = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +010055 FVP_PREBUILTS_TFA_ROOT, "fvp-base-gicv3-psci-1t.dts")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010056
Olivier Deprez1b1c4b62023-01-17 09:56:32 +010057FVP_PREBUILT_TFA_SPMD_ROOT = os.path.join(
58 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-spmd", "fvp")
Andrew Scull845fc9b2019-04-03 12:44:26 +010059
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +000060FVP_PREBUILTS_TFA_EL3_SPMC_ROOT = os.path.join(
61 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-el3-spmc")
J-Alves852fe742021-04-22 11:59:55 +010062VM_NODE_REGEX = "vm[1-9]"
63
Olivier Deprez3917deb2023-01-19 11:08:43 +010064QEMU_CPU_MAX = "max,pauth-impdef=true"
65
David Brazdil2df24082019-09-05 11:55:08 +010066def read_file(path):
67 with open(path, "r") as f:
68 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010069
David Brazdil2df24082019-09-05 11:55:08 +010070def write_file(path, to_write, append=False):
71 with open(path, "a" if append else "w") as f:
72 f.write(to_write)
73
74def append_file(path, to_write):
75 write_file(path, to_write, append=True)
76
77def join_if_not_None(*args):
78 return " ".join(filter(lambda x: x, args))
79
J-Alves852fe742021-04-22 11:59:55 +010080def get_vm_node_from_manifest(dts : str):
81 """ Get VM node string from Partition's extension to Partition Manager's
82 manifest."""
83 match = re.search(VM_NODE_REGEX, dts)
84 if not match:
85 raise Exception("Partition's node is not defined in its manifest.")
86 return match.group()
87
88def correct_vm_node(dts: str, node_index : int):
89 """ The vm node is being appended to the Partition Manager manifests.
90 Ideally, these files would be reused accross various test set-ups."""
91 return dts.replace(get_vm_node_from_manifest(dts), f"vm{node_index}")
92
J-Alves8cc7dbb2021-04-16 10:38:48 +010093DT = collections.namedtuple("DT", ["dts", "dtb"])
94
David Brazdil2df24082019-09-05 11:55:08 +010095class ArtifactsManager:
96 """Class which manages folder with test artifacts."""
97
98 def __init__(self, log_dir):
99 self.created_files = []
100 self.log_dir = log_dir
101
102 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +0100103 try:
David Brazdil2df24082019-09-05 11:55:08 +0100104 os.makedirs(self.log_dir)
105 except OSError:
106 if not os.path.isdir(self.log_dir):
107 raise
108 print("Logs saved under", log_dir)
109
110 # Create files expected by the Sponge test result parser.
111 self.sponge_log_path = self.create_file("sponge_log", ".log")
112 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
113
David Brazdil623b6812019-09-09 11:41:08 +0100114 def gen_file_path(self, basename, extension):
115 """Generate path to a file in the log directory."""
116 return os.path.join(self.log_dir, basename + extension)
117
David Brazdil2df24082019-09-05 11:55:08 +0100118 def create_file(self, basename, extension):
119 """Create and touch a new file in the log folder. Ensure that no other
120 file of the same name was created by this instance of ArtifactsManager.
121 """
122 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +0100123 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +0100124
125 # Check that the path is unique.
126 assert(path not in self.created_files)
127 self.created_files += [ path ]
128
129 # Touch file.
130 with open(path, "w") as f:
131 pass
132
133 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100134
David Brazdil623b6812019-09-09 11:41:08 +0100135 def get_file(self, basename, extension):
136 """Return path to a file in the log folder. Assert that it was created
137 by this instance of ArtifactsManager."""
138 path = self.gen_file_path(basename, extension)
139 assert(path in self.created_files)
140 return path
141
Andrew Scullbc7189d2018-08-14 09:35:13 +0100142
David Brazdil2df24082019-09-05 11:55:08 +0100143# Tuple holding the arguments common to all driver constructors.
144# This is to avoid having to pass arguments from subclasses to superclasses.
145DriverArgs = collections.namedtuple("DriverArgs", [
146 "artifacts",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100147 "hypervisor",
148 "spmc",
David Brazdil2df24082019-09-05 11:55:08 +0100149 "initrd",
150 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000151 "cpu",
J-Alves18a25f92021-05-04 17:47:41 +0100152 "partitions",
153 "global_run_name",
Saul Romero42a13632022-12-20 15:13:36 +0000154 "coverage_plugin",
David Brazdil2df24082019-09-05 11:55:08 +0100155 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100156
David Brazdil2df24082019-09-05 11:55:08 +0100157# State shared between the common Driver class and its subclasses during
158# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100159class DriverRunState:
160 def __init__(self, log_path):
161 self.log_path = log_path
162 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000163
David Brazdil7325eaf2019-09-27 13:04:51 +0100164 def set_ret_code(self, ret_code):
165 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000166
David Brazdil0dbb41f2019-09-09 18:03:35 +0100167class DriverRunException(Exception):
168 """Exception thrown if subprocess invoked by a driver returned non-zero
169 status code. Used to fast-exit from a driver command sequence."""
170 pass
171
172
David Brazdil2df24082019-09-05 11:55:08 +0100173class Driver:
174 """Parent class of drivers for all testable platforms."""
175
176 def __init__(self, args):
177 self.args = args
178
David Brazdil623b6812019-09-09 11:41:08 +0100179 def get_run_log(self, run_name):
180 """Return path to the main log of a given test run."""
181 return self.args.artifacts.get_file(run_name, ".log")
182
David Brazdil2df24082019-09-05 11:55:08 +0100183 def start_run(self, run_name):
184 """Hook called by Driver subclasses before they invoke the target
185 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100186 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100187
Andrew Walbranf636b842020-01-10 11:46:12 +0000188 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100189 """Run a subprocess on behalf of a Driver subclass and append its
190 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100191 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100192 with open(run_state.log_path, "a") as f:
193 f.write("$ {}\r\n".format(" ".join(exec_args)))
194 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000195 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100196 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100197 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100198 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100199
David Brazdil0dbb41f2019-09-09 18:03:35 +0100200 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100201 """Hook called by Driver subclasses after they finished running the
202 target platform. `ret_code` argument is the return code of the main
203 command run by the driver. A corresponding log message is printed."""
204 # Decode return code and add a message to the log.
205 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100206 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100207 f.write("\r\n{}{} timed out\r\n".format(
208 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100209 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100210 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100211 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
212 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100213
214 # Append log of this run to full test log.
215 log_content = read_file(run_state.log_path)
216 append_file(
217 self.args.artifacts.sponge_log_path,
218 log_content + "\r\n\r\n")
219 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000220
David Brazdil2df24082019-09-05 11:55:08 +0100221class QemuDriver(Driver):
222 """Driver which runs tests in QEMU."""
223
Andrew Walbranf636b842020-01-10 11:46:12 +0000224 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100225 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000226 self.qemu_wd = qemu_wd
227 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100228
David Brazdila2358d42020-01-27 18:51:38 +0000229 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100230 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100231 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000232 # If no CPU configuration is selected, then test against the maximum
233 # configuration, "max", supported by QEMU.
Olivier Deprez3917deb2023-01-19 11:08:43 +0100234 if not self.args.cpu or self.args.cpu == "max":
235 cpu = QEMU_CPU_MAX
236 else:
237 cpu = self.args.cpu
238
David Brazdil2df24082019-09-05 11:55:08 +0100239 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100240 "timeout", "--foreground", time_limit,
Olivier Depreze30c36f2022-11-22 11:26:47 +0100241 QEMU_PREBUILTS,
Olivier Deprez5373f232022-11-23 09:57:19 +0100242 "-no-reboot", "-machine", "virt-6.2,virtualization=on,gic-version=3",
J-Alves871e3732022-05-31 17:10:50 +0100243 "-cpu", cpu, "-smp", "8", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100244 "-nographic", "-nodefaults", "-serial", "stdio",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100245 "-d", "unimp", "-kernel", os.path.abspath(self.args.hypervisor),
David Brazdil2df24082019-09-05 11:55:08 +0100246 ]
247
Andrew Walbranf636b842020-01-10 11:46:12 +0000248 if self.tfa:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100249 bl1_path = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +0100250 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100251 "qemu", "bl1.bin")
Andrew Walbranf636b842020-01-10 11:46:12 +0000252 exec_args += ["-bios",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100253 os.path.abspath(bl1_path),
254 "-machine", "secure=on", "-semihosting-config",
Andrew Walbranab4b2d52020-06-11 16:54:10 +0100255 "enable=on,target=native"]
Andrew Walbranf636b842020-01-10 11:46:12 +0000256
David Brazdil2df24082019-09-05 11:55:08 +0100257 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000258 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100259
260 vm_args = join_if_not_None(self.args.vm_args, test_args)
261 if vm_args:
262 exec_args += ["-append", vm_args]
263
264 return exec_args
265
J-Alves67c31912023-02-02 13:52:50 +0000266 def run(self, run_name, test_args, is_long_running, debug = False,
267 show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100268 """Run test given by `test_args` in QEMU."""
J-Alves67c31912023-02-02 13:52:50 +0000269 # TODO: use 'debug' and 'show_output' flags.
David Brazdil2df24082019-09-05 11:55:08 +0100270 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100271
272 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100273 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000274 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000275 self.exec_logged(run_state, exec_args,
276 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100277 except DriverRunException:
278 pass
279
280 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100281
David Brazdil94fd1e92020-02-03 16:45:20 +0000282 def finish(self):
283 """Clean up after running tests."""
284 pass
285
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100286class FvpDriver(Driver, ABC):
287 """Base class for driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100288
J-Alves19216692023-05-12 15:01:31 +0100289 def __init__(self, args, cpu_start_address, fvp_prebuilt_bl31):
Saul Romero42a13632022-12-20 15:13:36 +0000290 self.cov_plugin = args.coverage_plugin or None
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000291 if args.cpu:
292 raise ValueError("FVP emulator does not support the --cpu option.")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100293 super().__init__(args)
J-Alves19216692023-05-12 15:01:31 +0100294 self._cpu_start_address = cpu_start_address
295 self._fvp_prebuilt_bl31 = fvp_prebuilt_bl31
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100296
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100297 def create_dt(self, run_name : str):
298 """Create DT related files, and return respective paths in a tuple
299 (dts,dtb)"""
J-Alves8cc7dbb2021-04-16 10:38:48 +0100300 return DT(self.args.artifacts.create_file(run_name, ".dts"),
301 self.args.artifacts.create_file(run_name, ".dtb"))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100302
J-Alves8cc7dbb2021-04-16 10:38:48 +0100303 def compile_dt(self, run_state, dt : DT):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100304 """Compile DT calling dtc."""
305 dtc_args = [
J-Alves8cc7dbb2021-04-16 10:38:48 +0100306 DTC_SCRIPT, "compile", "-i", dt.dts, "-o", dt.dtb,
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100307 ]
308 self.exec_logged(run_state, dtc_args)
309
310 def create_uart_log(self, run_name : str, file_name : str):
311 """Create uart log file, and return path"""
312 return self.args.artifacts.create_file(run_name, file_name)
313
314 def get_img_and_ldadd(self, partitions : dict):
315 ret = []
316 for i, p in enumerate(partitions):
J-Alves852fe742021-04-22 11:59:55 +0100317 with open(p["dts"], "r") as dt:
318 dts = dt.read()
319 manifest = fdt.parse_dts(dts)
320 vm_node = get_vm_node_from_manifest(dts)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100321 load_address = manifest.get_property("load_address",
J-Alves852fe742021-04-22 11:59:55 +0100322 f"/hypervisor/{vm_node}").value
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100323 ret.append((p["img"], load_address))
324 return ret
325
326 def get_manifests_from_json(self, partitions : list):
327 manifests = ""
328 if partitions is not None:
J-Alves852fe742021-04-22 11:59:55 +0100329 for i, p in enumerate(partitions):
330 manifests += correct_vm_node(read_file(p["dts"]), i + 1)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100331 return manifests
332
333 @abstractmethod
J-Alves8cc7dbb2021-04-16 10:38:48 +0100334 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100335 """Abstract method to generate dts file. This specific to the use case
336 so should be implemented within derived driver"""
337 pass
338
339 @abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +0100340 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000341 self, is_long_running, uart0_log_path, uart1_log_path, dt,
342 debug = False, show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100343 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000344 show_output = debug or show_output
Andrew Walbranee5418e2019-11-27 17:43:05 +0000345 time_limit = "80s" if is_long_running else "40s"
J-Alves67c31912023-02-02 13:52:50 +0000346 fvp_args = []
347
348 if not show_output:
349 fvp_args = [
350 "timeout", "--foreground", time_limit,
351 ]
352
353 fvp_args += [
David Brazdil2df24082019-09-05 11:55:08 +0100354 FVP_BINARY,
J-Alves10446d82021-04-26 11:52:57 +0100355 "-C", "pci.pci_smmuv3.mmu.SMMU_AIDR=2",
356 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR0=0x0046123B",
357 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR1=0x00600002",
358 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR3=0x1714",
359 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR5=0xFFFF0472",
360 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR1=0xA0000002",
361 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR2=0",
362 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR3=0",
David Brazdil2df24082019-09-05 11:55:08 +0100363 "-C", "pctl.startup=0.0.0.0",
Olivier Deprezcd857002022-05-09 09:06:24 +0200364 "-C", "bp.secure_memory=1",
David Brazdil2df24082019-09-05 11:55:08 +0100365 "-C", "cluster0.NUM_CORES=4",
366 "-C", "cluster1.NUM_CORES=4",
367 "-C", "cache_state_modelled=0",
David Brazdil2df24082019-09-05 11:55:08 +0100368 "-C", "bp.vis.rate_limit-enable=false",
David Brazdil2df24082019-09-05 11:55:08 +0100369 "-C", "bp.pl011_uart0.untimed_fifos=1",
370 "-C", "bp.pl011_uart0.unbuffered_output=1",
J-Alves19216692023-05-12 15:01:31 +0100371 "-C", f"cluster0.cpu0.RVBAR={self._cpu_start_address}",
372 "-C", f"cluster0.cpu1.RVBAR={self._cpu_start_address}",
373 "-C", f"cluster0.cpu2.RVBAR={self._cpu_start_address}",
374 "-C", f"cluster0.cpu3.RVBAR={self._cpu_start_address}",
375 "-C", f"cluster1.cpu0.RVBAR={self._cpu_start_address}",
376 "-C", f"cluster1.cpu1.RVBAR={self._cpu_start_address}",
377 "-C", f"cluster1.cpu2.RVBAR={self._cpu_start_address}",
378 "-C", f"cluster1.cpu3.RVBAR={self._cpu_start_address}",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100379 "--data",
J-Alves19216692023-05-12 15:01:31 +0100380 f"cluster0.cpu0={self._fvp_prebuilt_bl31}@{self._cpu_start_address}",
David Brazdil2df24082019-09-05 11:55:08 +0100381 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
Raghu Krishnamurthy75ebf8c2021-11-28 07:22:12 -0800382 "-C", "cluster0.has_arm_v8-5=1",
383 "-C", "cluster1.has_arm_v8-5=1",
384 "-C", "cluster0.has_branch_target_exception=1",
385 "-C", "cluster1.has_branch_target_exception=1",
Maksims Svecovsce1261f2022-03-04 15:22:58 +0000386 "-C", "cluster0.memory_tagging_support_level=2",
387 "-C", "cluster1.memory_tagging_support_level=2",
388 "-C", "bp.dram_metadata.is_enabled=1",
Raghu Krishnamurthye2eae292022-08-10 22:38:41 -0700389 "-C", "cluster0.gicv3.extended-interrupt-range-support=1",
390 "-C", "cluster1.gicv3.extended-interrupt-range-support=1",
391 "-C", "gic_distributor.extended-ppi-count=64",
392 "-C", "gic_distributor.extended-spi-count=1024",
393 "-C", "gic_distributor.ARE-fixed-to-one=1",
David Brazdil2df24082019-09-05 11:55:08 +0100394 ]
J-Alves18a25f92021-05-04 17:47:41 +0100395
396 if uart0_log_path and uart1_log_path:
397 fvp_args += [
398 "-C", f"bp.pl011_uart0.out_file={uart0_log_path}",
399 "-C", f"bp.pl011_uart1.out_file={uart1_log_path}",
400 ]
J-Alves67c31912023-02-02 13:52:50 +0000401
402 if not show_output:
403 fvp_args += [
404 "-C", "bp.vis.disable_visualisation=true",
405 "-C", "bp.terminal_0.start_telnet=false",
406 "-C", "bp.terminal_1.start_telnet=false",
407 "-C", "bp.terminal_2.start_telnet=false",
408 "-C", "bp.terminal_3.start_telnet=false",
409 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
410 ]
411
412 if debug:
413 fvp_args += [
Saul Romero42a13632022-12-20 15:13:36 +0000414 "-I", "-p"
415 ]
416
417 if self.cov_plugin is not None:
418 fvp_args += [
419 "--plugin", self.cov_plugin
J-Alves67c31912023-02-02 13:52:50 +0000420 ]
David Brazdil2df24082019-09-05 11:55:08 +0100421 return fvp_args
422
J-Alves67c31912023-02-02 13:52:50 +0000423 def run(self, run_name, test_args, is_long_running, debug = False,
424 show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100425 """ Run test """
David Brazdil2df24082019-09-05 11:55:08 +0100426 run_state = self.start_run(run_name)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100427 dt = self.create_dt(run_name)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100428 uart0_log_path = self.create_uart_log(run_name, ".uart0.log")
429 uart1_log_path = self.create_uart_log(run_name, ".uart1.log")
David Brazdil2df24082019-09-05 11:55:08 +0100430
David Brazdil0dbb41f2019-09-09 18:03:35 +0100431 try:
J-Alves8cc7dbb2021-04-16 10:38:48 +0100432 self.gen_dts(dt, test_args)
433 self.compile_dt(run_state, dt)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100434 fvp_args = self.gen_fvp_args(is_long_running, uart0_log_path,
J-Alves67c31912023-02-02 13:52:50 +0000435 uart1_log_path, dt, debug=debug,
436 show_output=show_output)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100437 self.exec_logged(run_state, fvp_args)
438 except DriverRunException:
439 pass
David Brazdil2df24082019-09-05 11:55:08 +0100440
441 # Append UART0 output to main log.
442 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100443 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100444
David Brazdil94fd1e92020-02-03 16:45:20 +0000445 def finish(self):
446 """Clean up after running tests."""
447 pass
448
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100449class FvpDriverHypervisor(FvpDriver):
450 """
451 Driver which runs tests in Arm FVP emulator, with hafnium as hypervisor
452 """
453 INITRD_START= 0x84000000
Olivier Depreza516f482021-04-30 18:47:59 +0200454 INITRD_END = 0x86000000 #Default value, however may change if initrd in args
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100455
J-Alves19216692023-05-12 15:01:31 +0100456 def __init__(self, args, hypervisor_address=0x80000000, hypervisor_dtb_address=0x82000000):
457 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILTS_TFA_ROOT, "bl31.bin")
458 FvpDriver.__init__(self, args, 0x04020000, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100459 self.vms_in_partitions_json = args.partitions and args.partitions["VMs"]
J-Alves19216692023-05-12 15:01:31 +0100460 self._hypervisor_address = hypervisor_address
461 self._hypervisor_dtb_address = hypervisor_dtb_address
J-Alves38223dd2021-04-20 17:31:48 +0100462
J-Alves8cc7dbb2021-04-16 10:38:48 +0100463 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100464 """Create a DeviceTree source which will be compiled into a DTB and
465 passed to FVP for a test run."""
466
467 vm_args = join_if_not_None(self.args.vm_args, test_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100468 write_file(dt.dts, read_file(FVP_PREBUILT_DTS))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100469
470 # Write the vm arguments to the partition manifest
471 to_append = f"""
472/ {{
473 chosen {{
474 bootargs = "{vm_args}";
475 stdout-path = "serial0:115200n8";
476 linux,initrd-start = <{self.INITRD_START if self.args.initrd else 0}>;
477 linux,initrd-end = <{self.INITRD_END if self.args.initrd else 0}>;
478 }};
479}};"""
480 if self.vms_in_partitions_json:
481 to_append += self.get_manifests_from_json(self.args.partitions["VMs"])
482
J-Alves8cc7dbb2021-04-16 10:38:48 +0100483 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100484
485 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000486 self, is_long_running, uart0_log_path, uart1_log_path, dt,
487 debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100488 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000489 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt,
490 debug, show_output)
491 fvp_args = FvpDriver.gen_fvp_args(*common_args)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100492
J-Alves8cc7dbb2021-04-16 10:38:48 +0100493 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100494 "--data", f"cluster0.cpu0={dt.dtb}@{self._hypervisor_dtb_address}",
495 "--data", f"cluster0.cpu0={self.args.hypervisor}@{self._hypervisor_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100496 ]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100497
498 if self.vms_in_partitions_json:
499 img_ldadd = self.get_img_and_ldadd(self.args.partitions["VMs"])
500 for img, ldadd in img_ldadd:
501 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
502
503 if self.args.initrd:
504 fvp_args += [
505 "--data",
506 f"cluster0.cpu0={self.args.initrd}@{self.INITRD_START}"
507 ]
508 return fvp_args
509
510class FvpDriverSPMC(FvpDriver):
511 """
512 Driver which runs tests in Arm FVP emulator, with hafnium as SPMC
513 """
514 FVP_PREBUILT_SECURE_DTS = os.path.join(
515 HF_ROOT, "test", "vmapi", "fvp-base-spmc.dts")
J-Alvesacdbb862023-01-31 17:14:55 +0000516 hftest_cmd_file = tempfile.NamedTemporaryFile(mode="w+")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100517
J-Alves19216692023-05-12 15:01:31 +0100518 def __init__(self, args, cpu_start_address=0x04010000, fvp_prebuilt_bl31=None):
519 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILT_TFA_SPMD_ROOT, "bl31.bin") if fvp_prebuilt_bl31 is None else fvp_prebuilt_bl31
520 super().__init__(args, cpu_start_address, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100521
J-Alves19216692023-05-12 15:01:31 +0100522 self._spmc_address = 0x6000000
523 self._spmc_dtb_address = 0x0403f000
J-Alves38223dd2021-04-20 17:31:48 +0100524
J-Alves8cc7dbb2021-04-16 10:38:48 +0100525 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100526 """Create a DeviceTree source which will be compiled into a DTB and
527 passed to FVP for a test run."""
528 to_append = self.get_manifests_from_json(self.args.partitions["SPs"])
J-Alves8cc7dbb2021-04-16 10:38:48 +0100529 write_file(dt.dts, read_file(FvpDriverSPMC.FVP_PREBUILT_SECURE_DTS))
530 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100531
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000532 def secure_ctrl_fvp_args(self, secure_ctrl):
533 fvp_args = ""
534 if secure_ctrl:
535 fvp_args = [
536 "-C", f"bp.pl011_uart0.in_file={FvpDriverSPMC.hftest_cmd_file.name}",
537 "-C", f"bp.pl011_uart0.shutdown_tag=\"{HFTEST_CTRL_FINISHED}\"",
538 ]
539 return fvp_args
540
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100541 def gen_fvp_args(
J-Alves8cc7dbb2021-04-16 10:38:48 +0100542 self, is_long_running, uart0_log_path, uart1_log_path, dt,
J-Alves67c31912023-02-02 13:52:50 +0000543 call_super = True, secure_ctrl = True, debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100544 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000545 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
546 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100547 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
J-Alves8cc7dbb2021-04-16 10:38:48 +0100548
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100549 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100550 "--data", f"cluster0.cpu0={dt.dtb}@{self._spmc_dtb_address}",
551 "--data", f"cluster0.cpu0={self.args.spmc}@{self._spmc_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100552 ]
553
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000554 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
J-Alves18a25f92021-05-04 17:47:41 +0100555
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100556 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
557 for img, ldadd in img_ldadd:
558 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
559
560 return fvp_args
561
J-Alves67c31912023-02-02 13:52:50 +0000562 def run(self, run_name, test_args, is_long_running, debug = False, show_output = False):
J-Alvesacdbb862023-01-31 17:14:55 +0000563 vm_args = join_if_not_None(self.args.vm_args, test_args)
564 FvpDriverSPMC.hftest_cmd_file.write(f"{vm_args}\n")
565 FvpDriverSPMC.hftest_cmd_file.seek(0)
J-Alves67c31912023-02-02 13:52:50 +0000566 return super().run(run_name, test_args, is_long_running, debug, show_output)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100567
568 def finish(self):
569 """Clean up after running tests."""
J-Alvesacdbb862023-01-31 17:14:55 +0000570 FvpDriverSPMC.hftest_cmd_file.close()
David Brazdil2df24082019-09-05 11:55:08 +0100571
J-Alves38223dd2021-04-20 17:31:48 +0100572class FvpDriverBothWorlds(FvpDriverHypervisor, FvpDriverSPMC):
573 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100574 FvpDriverHypervisor.__init__(self, args, hypervisor_address=0x88000000)
J-Alves38223dd2021-04-20 17:31:48 +0100575 FvpDriverSPMC.__init__(self, args)
576
J-Alves38223dd2021-04-20 17:31:48 +0100577 def create_dt(self, run_name):
578 dt = dict()
579 dt["hypervisor"] = FvpDriver.create_dt(self, run_name + "_hypervisor")
580 dt["spmc"] = FvpDriver.create_dt(self, run_name + "_spmc")
581 return dt
582
J-Alves38223dd2021-04-20 17:31:48 +0100583 def compile_dt(self, run_state, dt):
584 FvpDriver.compile_dt(self, run_state, dt["hypervisor"])
585 FvpDriver.compile_dt(self, run_state, dt["spmc"])
586
587 def gen_dts(self, dt, test_args):
588 FvpDriverHypervisor.gen_dts(self, dt["hypervisor"], test_args)
589 FvpDriverSPMC.gen_dts(self, dt["spmc"], test_args)
590
J-Alves67c31912023-02-02 13:52:50 +0000591 def gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
592 debug = False, show_output = False):
J-Alves38223dd2021-04-20 17:31:48 +0100593 """Generate command line arguments for FVP."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000594 common_args = (self, is_long_running, uart0_log_path, uart1_log_path)
J-Alves67c31912023-02-02 13:52:50 +0000595 fvp_args = FvpDriverHypervisor.gen_fvp_args(*common_args, dt["hypervisor"],
596 debug, show_output)
J-Alves18a25f92021-05-04 17:47:41 +0100597 fvp_args += FvpDriverSPMC.gen_fvp_args(*common_args, dt["spmc"], False,
598 False)
J-Alves8d9fbb92021-12-13 17:28:15 +0000599 return fvp_args
J-Alves18a25f92021-05-04 17:47:41 +0100600
J-Alves67c31912023-02-02 13:52:50 +0000601 def run(self, run_name, test_args, is_long_running, debug = False,
602 show_output = False):
603
604 return FvpDriver.run(self, run_name, test_args, is_long_running,
605 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100606
607 def finish(self):
608 """Clean up after running tests."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000609 FvpDriver.finish(self)
J-Alves38223dd2021-04-20 17:31:48 +0100610
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000611class FvpDriverEL3SPMC(FvpDriverSPMC):
612 """
613 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
614 """
615
616 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100617 FvpDriverSPMC.__init__(
618 self, args, cpu_start_address=0x04003000,
619 fvp_prebuilt_bl31=os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl31.bin"))
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000620 self.vms_in_partitions_json = args.partitions and args.partitions["SPs"]
J-Alves19216692023-05-12 15:01:31 +0100621 self._sp_dtb_address = 0x0403f000
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000622
623 def sp_partition_manifest_fvp_args(self):
624 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
625
626 # Expect only one tuple with img and load address, as EL3 SPMC only supports
627 # one SP.
628 assert(len(img_ldadd) == 1)
629 img, ldadd = img_ldadd[0]
630 fvp_args = ["--data", f"cluster0.cpu0={img}@{ldadd}"]
631
632 # Even though FF-A manifest is part of the SP PKG we need to load at a specific
633 # location. Fetch the respective dtb file and load at the following address.
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000634 output_path = os.path.dirname(os.path.dirname(img))
635 partition_manifest = f"{output_path}/partition-manifest.dtb"
J-Alves19216692023-05-12 15:01:31 +0100636 fvp_args += ["--data", f"cluster0.cpu0={partition_manifest}@{self._sp_dtb_address}"]
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000637 return fvp_args
638
639 def gen_fvp_args(
640 self, is_long_running, uart0_log_path, uart1_log_path, dt,
641 call_super = True, secure_ctrl = True, debug = False, show_output = False):
642 """Generate command line arguments for FVP."""
643 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
644 debug, show_output)
645 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
646
647 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
648
649 fvp_args += self.sp_partition_manifest_fvp_args()
650
651 return fvp_args
652
Shruti Gupta22dbef32023-04-03 10:26:31 +0100653class FvpDriverEL3SPMCBothWorlds(FvpDriverHypervisor, FvpDriverEL3SPMC):
654 """
655 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
656 """
657
J-Alves19216692023-05-12 15:01:31 +0100658 def __init__(self, args):
659 FvpDriverHypervisor.__init__(self, args)
660 FvpDriverEL3SPMC.__init__(self, args)
Shruti Gupta22dbef32023-04-03 10:26:31 +0100661
J-Alves19216692023-05-12 15:01:31 +0100662 self._fvp_prebuilt_bl32 = os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl32.bin")
663 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 +0100664
665 def gen_fvp_args(
666 self, is_long_running, uart0_log_path, uart1_log_path, dt,
667 call_super = True, secure_ctrl = True, debug = False, show_output = False):
668 """Generate command line arguments for FVP."""
669
670 fvp_args = FvpDriverHypervisor.gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
671 debug, show_output)
672
673 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
674
675 if self.args.partitions is not None and self.args.partitions["SPs"] is not None:
676 fvp_args += FvpDriverEL3SPMC.sp_partition_manifest_fvp_args(self)
677 else :
678 # Use prebuilt TSP and TSP manifest if build does not specify SP
679 # EL3 SPMC expects SP to be loaded at 0xFF200000 and SP manifest at 0x0403F000
J-Alves19216692023-05-12 15:01:31 +0100680 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_bl32}@0xff200000"]
681 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_dtb}@{self._sp_dtb_address}"]
Shruti Gupta22dbef32023-04-03 10:26:31 +0100682
683 return fvp_args
684
David Brazdil17e76652020-01-29 14:44:19 +0000685class SerialDriver(Driver):
686 """Driver which communicates with a device over the serial port."""
687
David Brazdil9d4ed962020-02-06 17:23:48 +0000688 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000689 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000690 self.tty_file = tty_file
691 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000692 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000693
David Brazdil9d4ed962020-02-06 17:23:48 +0000694 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000695 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000696
David Brazdil9d4ed962020-02-06 17:23:48 +0000697 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000698 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000699
David Brazdil17e76652020-01-29 14:44:19 +0000700 def run(self, run_name, test_args, is_long_running):
701 """Communicate `test_args` to the device over the serial port."""
702 run_state = self.start_run(run_name)
703
David Brazdil9d4ed962020-02-06 17:23:48 +0000704 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000705 with open(run_state.log_path, "a") as f:
706 while True:
707 # Read one line from the serial port.
708 line = ser.readline().decode('utf-8')
709 if len(line) == 0:
710 # Timeout
711 run_state.set_ret_code(124)
712 input("Timeout. " +
713 "Press ENTER and then reset the device...")
714 break
715 # Write the line to the log file.
716 f.write(line)
717 if HFTEST_CTRL_GET_COMMAND_LINE in line:
718 # Device is waiting for `test_args`.
719 ser.write(test_args.encode('ascii'))
720 ser.write(b'\r')
721 elif HFTEST_CTRL_FINISHED in line:
722 # Device has finished running this test and will reboot.
723 break
J-Alves18a25f92021-05-04 17:47:41 +0100724
David Brazdil17e76652020-01-29 14:44:19 +0000725 return self.finish_run(run_state)
726
David Brazdil94fd1e92020-02-03 16:45:20 +0000727 def finish(self):
728 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000729 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000730 while True:
731 line = ser.readline().decode('utf-8')
732 if len(line) == 0:
733 input("Timeout. Press ENTER and then reset the device...")
734 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
735 # Device is waiting for a command. Instruct it to exit
736 # the test environment.
737 ser.write("exit".encode('ascii'))
738 ser.write(b'\r')
739 break
740
David Brazdil2df24082019-09-05 11:55:08 +0100741# Tuple used to return information about the results of running a set of tests.
742TestRunnerResult = collections.namedtuple("TestRunnerResult", [
743 "tests_run",
744 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100745 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100746 ])
747
David Brazdil2df24082019-09-05 11:55:08 +0100748class TestRunner:
749 """Class which communicates with a test platform to obtain a list of
750 available tests and driving their execution."""
751
J-Alves8cc7dbb2021-04-16 10:38:48 +0100752 def __init__(self, artifacts, driver, test_set_up, suite_regex, test_regex,
J-Alves67c31912023-02-02 13:52:50 +0000753 skip_long_running_tests, force_long_running, debug, show_output):
David Brazdil2df24082019-09-05 11:55:08 +0100754 self.artifacts = artifacts
755 self.driver = driver
J-Alves8cc7dbb2021-04-16 10:38:48 +0100756 self.test_set_up = test_set_up
David Brazdil3cc24aa2019-09-27 10:24:41 +0100757 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100758 self.force_long_running = force_long_running
J-Alves67c31912023-02-02 13:52:50 +0000759 self.debug = debug
760 self.show_output = show_output
David Brazdil2df24082019-09-05 11:55:08 +0100761
762 self.suite_re = re.compile(suite_regex or ".*")
763 self.test_re = re.compile(test_regex or ".*")
764
765 def extract_hftest_lines(self, raw):
766 """Extract hftest-specific lines from a raw output from an invocation
767 of the test platform."""
768 lines = []
J-Alves07be7bb2021-04-13 11:09:12 +0100769 lines_to_process = raw.splitlines()
770
771 try:
772 # If logs have logs of more than one VM, the loop below to extract
773 # lines won't work. Thus, extracting between starting and ending
774 # logs: HFTEST_CTRL_GET_COMMAND_LINE and HFTEST_CTRL_FINISHED.
775 hftest_start = lines_to_process.index(HFTEST_CTRL_GET_COMMAND_LINE) + 1
776 hftest_end = lines_to_process.index(HFTEST_CTRL_FINISHED)
777 except ValueError:
778 hftest_start = 0
779 hftest_end = len(lines_to_process)
780
781 lines_to_process = lines_to_process[hftest_start : hftest_end]
782
783 for line in lines_to_process:
J-Alvesb882db92023-08-02 13:40:07 +0100784 match = re.search(f"^(VM|SP) \d+: ", line)
J-Alves3dbb8562020-12-01 10:45:37 +0000785 if match is not None:
786 line = line[match.end():]
David Brazdil2df24082019-09-05 11:55:08 +0100787 if line.startswith(HFTEST_LOG_PREFIX):
788 lines.append(line[len(HFTEST_LOG_PREFIX):])
789 return lines
790
791 def get_test_json(self):
792 """Invoke the test platform and request a JSON of available test and
793 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100794 out = self.driver.run("json", "json", self.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100795 hf_out = "\n".join(self.extract_hftest_lines(out))
796 try:
797 return json.loads(hf_out)
798 except ValueError as e:
799 print(out)
800 raise e
801
802 def collect_results(self, fn, it, xml_node):
803 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
804 Insert "tests" and "failures" nodes to `xml_node`."""
805 tests_run = 0
806 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100807 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100808 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100809 for i in it:
810 sub_result = fn(i)
811 assert(sub_result.tests_run >= sub_result.tests_failed)
812 tests_run += sub_result.tests_run
813 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100814 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100815 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100816
Andrew Walbranf9463922020-06-05 16:44:42 +0100817 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100818 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100819 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100820 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100821 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100822
823 def is_passed_test(self, test_out):
824 """Parse the output of a test and return True if it passed."""
825 return \
826 len(test_out) > 0 and \
827 test_out[-1] == HFTEST_LOG_FINISHED and \
828 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
829
Andrew Walbranf9463922020-06-05 16:44:42 +0100830 def get_failure_message(self, test_out):
831 """Parse the output of a test and return the message of the first
832 assertion failure."""
833 for i, line in enumerate(test_out):
834 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
835 # The assertion message is on the line after the 'Failure:'
836 return test_out[i + 1].strip()
837
838 return None
839
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000840 def get_log_name(self, suite, test):
841 """Returns a string with a generated log name for the test."""
842 log_name = ""
843
844 cpu = self.driver.args.cpu
845 if cpu:
846 log_name += cpu + "."
847
848 log_name += suite["name"] + "." + test["name"]
849
850 return log_name
851
David Brazdil2df24082019-09-05 11:55:08 +0100852 def run_test(self, suite, test, suite_xml):
853 """Invoke the test platform and request to run a given `test` in given
854 `suite`. Create a new XML node with results under `suite_xml`.
855 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100856 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100857 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100858
859 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100860 test_xml.set("name", test["name"])
861 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100862
J-Alvesd459b562022-12-05 14:56:33 +0000863 if (self.skip_long_running_tests and test["is_long_running"]) or test["skip_test"]:
Andrew Walbranf9463922020-06-05 16:44:42 +0100864 print(" SKIP", test["name"])
865 test_xml.set("status", "notrun")
866 skipped_xml = ET.SubElement(test_xml, "skipped")
867 skipped_xml.set("message", "Long running")
868 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
869
J-Alves67c31912023-02-02 13:52:50 +0000870 action_log = "DEBUG" if self.debug else "RUN"
871 print(f" {action_log}", test["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100872 log_name = self.get_log_name(suite, test)
873
David Brazdil2df24082019-09-05 11:55:08 +0100874 test_xml.set("status", "run")
875
Andrew Walbran42bf2842020-06-05 18:50:19 +0100876 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100877 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100878 log_name, "run {} {}".format(suite["name"], test["name"]),
J-Alves67c31912023-02-02 13:52:50 +0000879 test["is_long_running"] or self.force_long_running,
880 self.debug, self.show_output)
881
Andrew Walbranf9463922020-06-05 16:44:42 +0100882 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100883 elapsed_time = time.perf_counter() - start_time
884
885 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100886
Andrew Walbranf9463922020-06-05 16:44:42 +0100887 system_out_xml = ET.SubElement(test_xml, "system-out")
888 system_out_xml.text = out
889
890 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100891 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100892 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100893 else:
David Brazdil623b6812019-09-09 11:41:08 +0100894 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100895 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100896 failure_message = self.get_failure_message(hftest_out) or "Test failed"
897 failure_xml.set("message", failure_message)
898 failure_xml.text = '\n'.join(hftest_out)
899 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100900
901 def run_suite(self, suite, xml):
902 """Invoke the test platform and request to run all matching tests in
903 `suite`. Create new XML nodes with results under `xml`.
904 Suite skipped if it does not match the regex given to constructor."""
905 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100906 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100907
908 print(" SUITE", suite["name"])
909 suite_xml = ET.SubElement(xml, "testsuite")
910 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100911 properties_xml = ET.SubElement(suite_xml, "properties")
912
913 property_xml = ET.SubElement(properties_xml, "property")
914 property_xml.set("name", "driver")
915 property_xml.set("value", type(self.driver).__name__)
916
917 if self.driver.args.cpu:
918 property_xml = ET.SubElement(properties_xml, "property")
919 property_xml.set("name", "cpu")
920 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100921
922 return self.collect_results(
923 lambda test: self.run_test(suite, test, suite_xml),
924 suite["tests"],
925 suite_xml)
926
927 def run_tests(self):
928 """Run all suites and tests matching regexes given to constructor.
929 Write results to sponge log XML. Return the number of run and failed
930 tests."""
931
932 test_spec = self.get_test_json()
933 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
934
935 xml = ET.Element("testsuites")
J-Alves8cc7dbb2021-04-16 10:38:48 +0100936 xml.set("name", self.test_set_up)
David Brazdil2df24082019-09-05 11:55:08 +0100937 xml.set("timestamp", timestamp)
938
939 result = self.collect_results(
940 lambda suite: self.run_suite(suite, xml),
941 test_spec["suites"],
942 xml)
943
944 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000945 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
946 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100947
948 if result.tests_failed > 0:
949 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
950 "tests failed")
951 elif result.tests_run > 0:
952 print(" PASS: all", result.tests_run, "tests passed")
953
David Brazdil94fd1e92020-02-03 16:45:20 +0000954 # Let the driver clean up.
955 self.driver.finish()
956
David Brazdil2df24082019-09-05 11:55:08 +0100957 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100958
Andrew Scullbc7189d2018-08-14 09:35:13 +0100959def Main():
960 parser = argparse.ArgumentParser()
J-Alves8cc7dbb2021-04-16 10:38:48 +0100961 parser.add_argument("--hypervisor")
962 parser.add_argument("--spmc")
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000963 parser.add_argument("--el3_spmc", action="store_true")
Andrew Scull23e93a82018-10-26 14:56:04 +0100964 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100965 parser.add_argument("--out_initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100966 parser.add_argument("--out_partitions")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000967 parser.add_argument("--initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100968 parser.add_argument("--partitions_json")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100969 parser.add_argument("--suite")
970 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000971 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000972 parser.add_argument("--driver", default="qemu")
973 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
974 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000975 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100976 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100977 parser.add_argument("--force-long-running", action="store_true")
J-Alves67c31912023-02-02 13:52:50 +0000978 parser.add_argument("--debug", action="store_true",
979 help="Makes platforms stall waiting for debugger connection.")
980 parser.add_argument("--show-output", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000981 parser.add_argument("--cpu",
982 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000983 parser.add_argument("--tfa", action="store_true")
Saul Romero42a13632022-12-20 15:13:36 +0000984 parser.add_argument("--coverage_plugin", default="")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100985 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100986
J-Alves8cc7dbb2021-04-16 10:38:48 +0100987 # Create class which will manage all test artifacts.
988 if args.hypervisor and args.spmc:
989 test_set_up = "hypervisor_and_spmc"
990 elif args.hypervisor:
991 test_set_up = "hypervisor"
992 elif args.spmc:
993 test_set_up = "spmc"
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000994 elif args.el3_spmc:
995 test_set_up = "el3_spmc"
J-Alves8cc7dbb2021-04-16 10:38:48 +0100996 else:
997 raise Exception("No Hafnium image provided!\n")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100998
J-Alves8cc7dbb2021-04-16 10:38:48 +0100999 initrd = None
1000 if args.hypervisor and args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +01001001 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
1002 initrd = os.path.join(initrd_dir, "initrd.img")
J-Alves8cc7dbb2021-04-16 10:38:48 +01001003 test_set_up += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +00001004 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +01001005
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001006 partitions = None
J-Alves18a25f92021-05-04 17:47:41 +01001007 global_run_name = None
1008 if args.driver == "fvp":
1009 if args.partitions_json is not None:
1010 partitions_dir = os.path.join(
1011 args.out_partitions, "obj", args.partitions_json)
1012 partitions = json.load(open(partitions_dir, "r"))
1013 global_run_name = os.path.basename(args.partitions_json).split(".")[0]
1014 elif args.hypervisor:
1015 if args.initrd:
1016 global_run_name = os.path.basename(args.initrd)
1017 else:
1018 global_run_name = os.path.basename(args.hypervisor).split(".")[0]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001019
David Brazdil2df24082019-09-05 11:55:08 +01001020 # Create class which will manage all test artifacts.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001021 log_dir = os.path.join(args.log, test_set_up)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001022 artifacts = ArtifactsManager(log_dir)
David Brazdil2df24082019-09-05 11:55:08 +01001023
1024 # Create a driver for the platform we want to test on.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001025 driver_args = DriverArgs(artifacts, args.hypervisor, args.spmc, initrd,
Saul Romero42a13632022-12-20 15:13:36 +00001026 vm_args, args.cpu, partitions, global_run_name,
1027 args.coverage_plugin)
David Brazdil17e76652020-01-29 14:44:19 +00001028
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001029 if args.el3_spmc:
J-Alves38223dd2021-04-20 17:31:48 +01001030 # So far only FVP supports tests for SPMC.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001031 if args.driver != "fvp":
1032 raise Exception("Secure tests can only run with fvp driver")
Shruti Gupta22dbef32023-04-03 10:26:31 +01001033 if args.hypervisor:
1034 driver = FvpDriverEL3SPMCBothWorlds(driver_args)
1035 else:
1036 driver = FvpDriverEL3SPMC(driver_args)
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001037 elif args.spmc:
1038 # So far only FVP supports tests for SPMC.
1039 if args.driver != "fvp":
1040 raise Exception("Secure tests can only run with fvp driver")
J-Alves38223dd2021-04-20 17:31:48 +01001041 if args.hypervisor:
1042 driver = FvpDriverBothWorlds(driver_args)
1043 else:
1044 driver = FvpDriverSPMC(driver_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +01001045 elif args.hypervisor:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001046 if args.driver == "qemu":
J-Alves8cc7dbb2021-04-16 10:38:48 +01001047 out = os.path.dirname(args.hypervisor)
1048 driver = QemuDriver(driver_args, out, args.tfa)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001049 elif args.driver == "fvp":
1050 driver = FvpDriverHypervisor(driver_args)
1051 elif args.driver == "serial":
1052 driver = SerialDriver(driver_args, args.serial_dev,
1053 args.serial_baudrate, not args.serial_no_init_wait)
1054 else:
1055 raise Exception("Unknown driver name: {}".format(args.driver))
J-Alves8cc7dbb2021-04-16 10:38:48 +01001056 else:
1057 raise Exception("No Hafnium image provided!\n")
David Brazdil2df24082019-09-05 11:55:08 +01001058
1059 # Create class which will drive test execution.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001060 runner = TestRunner(artifacts, driver, test_set_up, args.suite, args.test,
J-Alves67c31912023-02-02 13:52:50 +00001061 args.skip_long_running_tests, args.force_long_running, args.debug, args.show_output)
David Brazdil2df24082019-09-05 11:55:08 +01001062
1063 # Run tests.
1064 runner_result = runner.run_tests()
1065
1066 # Print error message if no tests were run as this is probably unexpected.
1067 # Return suitable error code.
1068 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001069 print("Error: no tests match")
1070 return 10
David Brazdil2df24082019-09-05 11:55:08 +01001071 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001072 return 1
1073 else:
David Brazdil2df24082019-09-05 11:55:08 +01001074 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +01001075
1076if __name__ == "__main__":
1077 sys.exit(Main())