blob: 8deaee64f9a72e195e7856a9e867d205ffe7ed01 [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",
David Brazdil2df24082019-09-05 11:55:08 +0100154 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100155
David Brazdil2df24082019-09-05 11:55:08 +0100156# State shared between the common Driver class and its subclasses during
157# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100158class DriverRunState:
159 def __init__(self, log_path):
160 self.log_path = log_path
161 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000162
David Brazdil7325eaf2019-09-27 13:04:51 +0100163 def set_ret_code(self, ret_code):
164 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000165
David Brazdil0dbb41f2019-09-09 18:03:35 +0100166class DriverRunException(Exception):
167 """Exception thrown if subprocess invoked by a driver returned non-zero
168 status code. Used to fast-exit from a driver command sequence."""
169 pass
170
171
David Brazdil2df24082019-09-05 11:55:08 +0100172class Driver:
173 """Parent class of drivers for all testable platforms."""
174
175 def __init__(self, args):
176 self.args = args
177
David Brazdil623b6812019-09-09 11:41:08 +0100178 def get_run_log(self, run_name):
179 """Return path to the main log of a given test run."""
180 return self.args.artifacts.get_file(run_name, ".log")
181
David Brazdil2df24082019-09-05 11:55:08 +0100182 def start_run(self, run_name):
183 """Hook called by Driver subclasses before they invoke the target
184 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100185 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100186
Andrew Walbranf636b842020-01-10 11:46:12 +0000187 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100188 """Run a subprocess on behalf of a Driver subclass and append its
189 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100190 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100191 with open(run_state.log_path, "a") as f:
192 f.write("$ {}\r\n".format(" ".join(exec_args)))
193 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000194 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100195 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100196 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100197 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100198
David Brazdil0dbb41f2019-09-09 18:03:35 +0100199 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100200 """Hook called by Driver subclasses after they finished running the
201 target platform. `ret_code` argument is the return code of the main
202 command run by the driver. A corresponding log message is printed."""
203 # Decode return code and add a message to the log.
204 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100205 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100206 f.write("\r\n{}{} timed out\r\n".format(
207 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100208 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100209 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100210 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
211 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100212
213 # Append log of this run to full test log.
214 log_content = read_file(run_state.log_path)
215 append_file(
216 self.args.artifacts.sponge_log_path,
217 log_content + "\r\n\r\n")
218 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000219
David Brazdil2df24082019-09-05 11:55:08 +0100220class QemuDriver(Driver):
221 """Driver which runs tests in QEMU."""
222
Andrew Walbranf636b842020-01-10 11:46:12 +0000223 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100224 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000225 self.qemu_wd = qemu_wd
226 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100227
David Brazdila2358d42020-01-27 18:51:38 +0000228 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100229 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100230 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000231 # If no CPU configuration is selected, then test against the maximum
232 # configuration, "max", supported by QEMU.
Olivier Deprez3917deb2023-01-19 11:08:43 +0100233 if not self.args.cpu or self.args.cpu == "max":
234 cpu = QEMU_CPU_MAX
235 else:
236 cpu = self.args.cpu
237
David Brazdil2df24082019-09-05 11:55:08 +0100238 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100239 "timeout", "--foreground", time_limit,
Olivier Depreze30c36f2022-11-22 11:26:47 +0100240 QEMU_PREBUILTS,
Olivier Deprez5373f232022-11-23 09:57:19 +0100241 "-no-reboot", "-machine", "virt-6.2,virtualization=on,gic-version=3",
J-Alves871e3732022-05-31 17:10:50 +0100242 "-cpu", cpu, "-smp", "8", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100243 "-nographic", "-nodefaults", "-serial", "stdio",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100244 "-d", "unimp", "-kernel", os.path.abspath(self.args.hypervisor),
David Brazdil2df24082019-09-05 11:55:08 +0100245 ]
246
Andrew Walbranf636b842020-01-10 11:46:12 +0000247 if self.tfa:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100248 bl1_path = os.path.join(
Olivier Deprez0c5e7dc2023-01-17 10:29:04 +0100249 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100250 "qemu", "bl1.bin")
Andrew Walbranf636b842020-01-10 11:46:12 +0000251 exec_args += ["-bios",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100252 os.path.abspath(bl1_path),
253 "-machine", "secure=on", "-semihosting-config",
Andrew Walbranab4b2d52020-06-11 16:54:10 +0100254 "enable=on,target=native"]
Andrew Walbranf636b842020-01-10 11:46:12 +0000255
David Brazdil2df24082019-09-05 11:55:08 +0100256 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000257 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100258
259 vm_args = join_if_not_None(self.args.vm_args, test_args)
260 if vm_args:
261 exec_args += ["-append", vm_args]
262
263 return exec_args
264
J-Alves67c31912023-02-02 13:52:50 +0000265 def run(self, run_name, test_args, is_long_running, debug = False,
266 show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100267 """Run test given by `test_args` in QEMU."""
J-Alves67c31912023-02-02 13:52:50 +0000268 # TODO: use 'debug' and 'show_output' flags.
David Brazdil2df24082019-09-05 11:55:08 +0100269 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100270
271 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100272 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000273 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000274 self.exec_logged(run_state, exec_args,
275 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100276 except DriverRunException:
277 pass
278
279 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100280
David Brazdil94fd1e92020-02-03 16:45:20 +0000281 def finish(self):
282 """Clean up after running tests."""
283 pass
284
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100285class FvpDriver(Driver, ABC):
286 """Base class for driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100287
J-Alves19216692023-05-12 15:01:31 +0100288 def __init__(self, args, cpu_start_address, fvp_prebuilt_bl31):
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000289 if args.cpu:
290 raise ValueError("FVP emulator does not support the --cpu option.")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100291 super().__init__(args)
J-Alves19216692023-05-12 15:01:31 +0100292 self._cpu_start_address = cpu_start_address
293 self._fvp_prebuilt_bl31 = fvp_prebuilt_bl31
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100294
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100295 def create_dt(self, run_name : str):
296 """Create DT related files, and return respective paths in a tuple
297 (dts,dtb)"""
J-Alves8cc7dbb2021-04-16 10:38:48 +0100298 return DT(self.args.artifacts.create_file(run_name, ".dts"),
299 self.args.artifacts.create_file(run_name, ".dtb"))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100300
J-Alves8cc7dbb2021-04-16 10:38:48 +0100301 def compile_dt(self, run_state, dt : DT):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100302 """Compile DT calling dtc."""
303 dtc_args = [
J-Alves8cc7dbb2021-04-16 10:38:48 +0100304 DTC_SCRIPT, "compile", "-i", dt.dts, "-o", dt.dtb,
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100305 ]
306 self.exec_logged(run_state, dtc_args)
307
308 def create_uart_log(self, run_name : str, file_name : str):
309 """Create uart log file, and return path"""
310 return self.args.artifacts.create_file(run_name, file_name)
311
312 def get_img_and_ldadd(self, partitions : dict):
313 ret = []
314 for i, p in enumerate(partitions):
J-Alves852fe742021-04-22 11:59:55 +0100315 with open(p["dts"], "r") as dt:
316 dts = dt.read()
317 manifest = fdt.parse_dts(dts)
318 vm_node = get_vm_node_from_manifest(dts)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100319 load_address = manifest.get_property("load_address",
J-Alves852fe742021-04-22 11:59:55 +0100320 f"/hypervisor/{vm_node}").value
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100321 ret.append((p["img"], load_address))
322 return ret
323
324 def get_manifests_from_json(self, partitions : list):
325 manifests = ""
326 if partitions is not None:
J-Alves852fe742021-04-22 11:59:55 +0100327 for i, p in enumerate(partitions):
328 manifests += correct_vm_node(read_file(p["dts"]), i + 1)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100329 return manifests
330
331 @abstractmethod
J-Alves8cc7dbb2021-04-16 10:38:48 +0100332 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100333 """Abstract method to generate dts file. This specific to the use case
334 so should be implemented within derived driver"""
335 pass
336
337 @abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +0100338 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000339 self, is_long_running, uart0_log_path, uart1_log_path, dt,
340 debug = False, show_output = False):
David Brazdil2df24082019-09-05 11:55:08 +0100341 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000342 show_output = debug or show_output
Andrew Walbranee5418e2019-11-27 17:43:05 +0000343 time_limit = "80s" if is_long_running else "40s"
J-Alves67c31912023-02-02 13:52:50 +0000344 fvp_args = []
345
346 if not show_output:
347 fvp_args = [
348 "timeout", "--foreground", time_limit,
349 ]
350
351 fvp_args += [
David Brazdil2df24082019-09-05 11:55:08 +0100352 FVP_BINARY,
J-Alves10446d82021-04-26 11:52:57 +0100353 "-C", "pci.pci_smmuv3.mmu.SMMU_AIDR=2",
354 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR0=0x0046123B",
355 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR1=0x00600002",
356 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR3=0x1714",
357 "-C", "pci.pci_smmuv3.mmu.SMMU_IDR5=0xFFFF0472",
358 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR1=0xA0000002",
359 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR2=0",
360 "-C", "pci.pci_smmuv3.mmu.SMMU_S_IDR3=0",
David Brazdil2df24082019-09-05 11:55:08 +0100361 "-C", "pctl.startup=0.0.0.0",
Olivier Deprezcd857002022-05-09 09:06:24 +0200362 "-C", "bp.secure_memory=1",
David Brazdil2df24082019-09-05 11:55:08 +0100363 "-C", "cluster0.NUM_CORES=4",
364 "-C", "cluster1.NUM_CORES=4",
365 "-C", "cache_state_modelled=0",
David Brazdil2df24082019-09-05 11:55:08 +0100366 "-C", "bp.vis.rate_limit-enable=false",
David Brazdil2df24082019-09-05 11:55:08 +0100367 "-C", "bp.pl011_uart0.untimed_fifos=1",
368 "-C", "bp.pl011_uart0.unbuffered_output=1",
J-Alves19216692023-05-12 15:01:31 +0100369 "-C", f"cluster0.cpu0.RVBAR={self._cpu_start_address}",
370 "-C", f"cluster0.cpu1.RVBAR={self._cpu_start_address}",
371 "-C", f"cluster0.cpu2.RVBAR={self._cpu_start_address}",
372 "-C", f"cluster0.cpu3.RVBAR={self._cpu_start_address}",
373 "-C", f"cluster1.cpu0.RVBAR={self._cpu_start_address}",
374 "-C", f"cluster1.cpu1.RVBAR={self._cpu_start_address}",
375 "-C", f"cluster1.cpu2.RVBAR={self._cpu_start_address}",
376 "-C", f"cluster1.cpu3.RVBAR={self._cpu_start_address}",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100377 "--data",
J-Alves19216692023-05-12 15:01:31 +0100378 f"cluster0.cpu0={self._fvp_prebuilt_bl31}@{self._cpu_start_address}",
David Brazdil2df24082019-09-05 11:55:08 +0100379 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
Raghu Krishnamurthy75ebf8c2021-11-28 07:22:12 -0800380 "-C", "cluster0.has_arm_v8-5=1",
381 "-C", "cluster1.has_arm_v8-5=1",
382 "-C", "cluster0.has_branch_target_exception=1",
383 "-C", "cluster1.has_branch_target_exception=1",
Maksims Svecovsce1261f2022-03-04 15:22:58 +0000384 "-C", "cluster0.memory_tagging_support_level=2",
385 "-C", "cluster1.memory_tagging_support_level=2",
386 "-C", "bp.dram_metadata.is_enabled=1",
Raghu Krishnamurthye2eae292022-08-10 22:38:41 -0700387 "-C", "cluster0.gicv3.extended-interrupt-range-support=1",
388 "-C", "cluster1.gicv3.extended-interrupt-range-support=1",
389 "-C", "gic_distributor.extended-ppi-count=64",
390 "-C", "gic_distributor.extended-spi-count=1024",
391 "-C", "gic_distributor.ARE-fixed-to-one=1",
David Brazdil2df24082019-09-05 11:55:08 +0100392 ]
J-Alves18a25f92021-05-04 17:47:41 +0100393
394 if uart0_log_path and uart1_log_path:
395 fvp_args += [
396 "-C", f"bp.pl011_uart0.out_file={uart0_log_path}",
397 "-C", f"bp.pl011_uart1.out_file={uart1_log_path}",
398 ]
J-Alves67c31912023-02-02 13:52:50 +0000399
400 if not show_output:
401 fvp_args += [
402 "-C", "bp.vis.disable_visualisation=true",
403 "-C", "bp.terminal_0.start_telnet=false",
404 "-C", "bp.terminal_1.start_telnet=false",
405 "-C", "bp.terminal_2.start_telnet=false",
406 "-C", "bp.terminal_3.start_telnet=false",
407 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
408 ]
409
410 if debug:
411 fvp_args += [
412 "-I", "-p",
413 ]
David Brazdil2df24082019-09-05 11:55:08 +0100414 return fvp_args
415
J-Alves67c31912023-02-02 13:52:50 +0000416 def run(self, run_name, test_args, is_long_running, debug = False,
417 show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100418 """ Run test """
David Brazdil2df24082019-09-05 11:55:08 +0100419 run_state = self.start_run(run_name)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100420 dt = self.create_dt(run_name)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100421 uart0_log_path = self.create_uart_log(run_name, ".uart0.log")
422 uart1_log_path = self.create_uart_log(run_name, ".uart1.log")
David Brazdil2df24082019-09-05 11:55:08 +0100423
David Brazdil0dbb41f2019-09-09 18:03:35 +0100424 try:
J-Alves8cc7dbb2021-04-16 10:38:48 +0100425 self.gen_dts(dt, test_args)
426 self.compile_dt(run_state, dt)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100427 fvp_args = self.gen_fvp_args(is_long_running, uart0_log_path,
J-Alves67c31912023-02-02 13:52:50 +0000428 uart1_log_path, dt, debug=debug,
429 show_output=show_output)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100430 self.exec_logged(run_state, fvp_args)
431 except DriverRunException:
432 pass
David Brazdil2df24082019-09-05 11:55:08 +0100433
434 # Append UART0 output to main log.
435 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100436 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100437
David Brazdil94fd1e92020-02-03 16:45:20 +0000438 def finish(self):
439 """Clean up after running tests."""
440 pass
441
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100442class FvpDriverHypervisor(FvpDriver):
443 """
444 Driver which runs tests in Arm FVP emulator, with hafnium as hypervisor
445 """
446 INITRD_START= 0x84000000
Olivier Depreza516f482021-04-30 18:47:59 +0200447 INITRD_END = 0x86000000 #Default value, however may change if initrd in args
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100448
J-Alves19216692023-05-12 15:01:31 +0100449 def __init__(self, args, hypervisor_address=0x80000000, hypervisor_dtb_address=0x82000000):
450 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILTS_TFA_ROOT, "bl31.bin")
451 FvpDriver.__init__(self, args, 0x04020000, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100452 self.vms_in_partitions_json = args.partitions and args.partitions["VMs"]
J-Alves19216692023-05-12 15:01:31 +0100453 self._hypervisor_address = hypervisor_address
454 self._hypervisor_dtb_address = hypervisor_dtb_address
J-Alves38223dd2021-04-20 17:31:48 +0100455
J-Alves8cc7dbb2021-04-16 10:38:48 +0100456 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100457 """Create a DeviceTree source which will be compiled into a DTB and
458 passed to FVP for a test run."""
459
460 vm_args = join_if_not_None(self.args.vm_args, test_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +0100461 write_file(dt.dts, read_file(FVP_PREBUILT_DTS))
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100462
463 # Write the vm arguments to the partition manifest
464 to_append = f"""
465/ {{
466 chosen {{
467 bootargs = "{vm_args}";
468 stdout-path = "serial0:115200n8";
469 linux,initrd-start = <{self.INITRD_START if self.args.initrd else 0}>;
470 linux,initrd-end = <{self.INITRD_END if self.args.initrd else 0}>;
471 }};
472}};"""
473 if self.vms_in_partitions_json:
474 to_append += self.get_manifests_from_json(self.args.partitions["VMs"])
475
J-Alves8cc7dbb2021-04-16 10:38:48 +0100476 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100477
478 def gen_fvp_args(
J-Alves67c31912023-02-02 13:52:50 +0000479 self, is_long_running, uart0_log_path, uart1_log_path, dt,
480 debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100481 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000482 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt,
483 debug, show_output)
484 fvp_args = FvpDriver.gen_fvp_args(*common_args)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100485
J-Alves8cc7dbb2021-04-16 10:38:48 +0100486 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100487 "--data", f"cluster0.cpu0={dt.dtb}@{self._hypervisor_dtb_address}",
488 "--data", f"cluster0.cpu0={self.args.hypervisor}@{self._hypervisor_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100489 ]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100490
491 if self.vms_in_partitions_json:
492 img_ldadd = self.get_img_and_ldadd(self.args.partitions["VMs"])
493 for img, ldadd in img_ldadd:
494 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
495
496 if self.args.initrd:
497 fvp_args += [
498 "--data",
499 f"cluster0.cpu0={self.args.initrd}@{self.INITRD_START}"
500 ]
501 return fvp_args
502
503class FvpDriverSPMC(FvpDriver):
504 """
505 Driver which runs tests in Arm FVP emulator, with hafnium as SPMC
506 """
507 FVP_PREBUILT_SECURE_DTS = os.path.join(
508 HF_ROOT, "test", "vmapi", "fvp-base-spmc.dts")
J-Alvesacdbb862023-01-31 17:14:55 +0000509 hftest_cmd_file = tempfile.NamedTemporaryFile(mode="w+")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100510
J-Alves19216692023-05-12 15:01:31 +0100511 def __init__(self, args, cpu_start_address=0x04010000, fvp_prebuilt_bl31=None):
512 fvp_prebuilt_bl31 = os.path.join(FVP_PREBUILT_TFA_SPMD_ROOT, "bl31.bin") if fvp_prebuilt_bl31 is None else fvp_prebuilt_bl31
513 super().__init__(args, cpu_start_address, fvp_prebuilt_bl31)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100514
J-Alves19216692023-05-12 15:01:31 +0100515 self._spmc_address = 0x6000000
516 self._spmc_dtb_address = 0x0403f000
J-Alves38223dd2021-04-20 17:31:48 +0100517
J-Alves8cc7dbb2021-04-16 10:38:48 +0100518 def gen_dts(self, dt, test_args):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100519 """Create a DeviceTree source which will be compiled into a DTB and
520 passed to FVP for a test run."""
521 to_append = self.get_manifests_from_json(self.args.partitions["SPs"])
J-Alves8cc7dbb2021-04-16 10:38:48 +0100522 write_file(dt.dts, read_file(FvpDriverSPMC.FVP_PREBUILT_SECURE_DTS))
523 append_file(dt.dts, to_append)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100524
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000525 def secure_ctrl_fvp_args(self, secure_ctrl):
526 fvp_args = ""
527 if secure_ctrl:
528 fvp_args = [
529 "-C", f"bp.pl011_uart0.in_file={FvpDriverSPMC.hftest_cmd_file.name}",
530 "-C", f"bp.pl011_uart0.shutdown_tag=\"{HFTEST_CTRL_FINISHED}\"",
531 ]
532 return fvp_args
533
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100534 def gen_fvp_args(
J-Alves8cc7dbb2021-04-16 10:38:48 +0100535 self, is_long_running, uart0_log_path, uart1_log_path, dt,
J-Alves67c31912023-02-02 13:52:50 +0000536 call_super = True, secure_ctrl = True, debug = False, show_output = False):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100537 """Generate command line arguments for FVP."""
J-Alves67c31912023-02-02 13:52:50 +0000538 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
539 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100540 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
J-Alves8cc7dbb2021-04-16 10:38:48 +0100541
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100542 fvp_args += [
J-Alves19216692023-05-12 15:01:31 +0100543 "--data", f"cluster0.cpu0={dt.dtb}@{self._spmc_dtb_address}",
544 "--data", f"cluster0.cpu0={self.args.spmc}@{self._spmc_address}",
J-Alves8cc7dbb2021-04-16 10:38:48 +0100545 ]
546
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000547 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
J-Alves18a25f92021-05-04 17:47:41 +0100548
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100549 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
550 for img, ldadd in img_ldadd:
551 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
552
553 return fvp_args
554
J-Alves67c31912023-02-02 13:52:50 +0000555 def run(self, run_name, test_args, is_long_running, debug = False, show_output = False):
J-Alvesacdbb862023-01-31 17:14:55 +0000556 vm_args = join_if_not_None(self.args.vm_args, test_args)
557 FvpDriverSPMC.hftest_cmd_file.write(f"{vm_args}\n")
558 FvpDriverSPMC.hftest_cmd_file.seek(0)
J-Alves67c31912023-02-02 13:52:50 +0000559 return super().run(run_name, test_args, is_long_running, debug, show_output)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100560
561 def finish(self):
562 """Clean up after running tests."""
J-Alvesacdbb862023-01-31 17:14:55 +0000563 FvpDriverSPMC.hftest_cmd_file.close()
David Brazdil2df24082019-09-05 11:55:08 +0100564
J-Alves38223dd2021-04-20 17:31:48 +0100565class FvpDriverBothWorlds(FvpDriverHypervisor, FvpDriverSPMC):
566 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100567 FvpDriverHypervisor.__init__(self, args, hypervisor_address=0x88000000)
J-Alves38223dd2021-04-20 17:31:48 +0100568 FvpDriverSPMC.__init__(self, args)
569
J-Alves38223dd2021-04-20 17:31:48 +0100570 def create_dt(self, run_name):
571 dt = dict()
572 dt["hypervisor"] = FvpDriver.create_dt(self, run_name + "_hypervisor")
573 dt["spmc"] = FvpDriver.create_dt(self, run_name + "_spmc")
574 return dt
575
J-Alves38223dd2021-04-20 17:31:48 +0100576 def compile_dt(self, run_state, dt):
577 FvpDriver.compile_dt(self, run_state, dt["hypervisor"])
578 FvpDriver.compile_dt(self, run_state, dt["spmc"])
579
580 def gen_dts(self, dt, test_args):
581 FvpDriverHypervisor.gen_dts(self, dt["hypervisor"], test_args)
582 FvpDriverSPMC.gen_dts(self, dt["spmc"], test_args)
583
J-Alves67c31912023-02-02 13:52:50 +0000584 def gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
585 debug = False, show_output = False):
J-Alves38223dd2021-04-20 17:31:48 +0100586 """Generate command line arguments for FVP."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000587 common_args = (self, is_long_running, uart0_log_path, uart1_log_path)
J-Alves67c31912023-02-02 13:52:50 +0000588 fvp_args = FvpDriverHypervisor.gen_fvp_args(*common_args, dt["hypervisor"],
589 debug, show_output)
J-Alves18a25f92021-05-04 17:47:41 +0100590 fvp_args += FvpDriverSPMC.gen_fvp_args(*common_args, dt["spmc"], False,
591 False)
J-Alves8d9fbb92021-12-13 17:28:15 +0000592 return fvp_args
J-Alves18a25f92021-05-04 17:47:41 +0100593
J-Alves67c31912023-02-02 13:52:50 +0000594 def run(self, run_name, test_args, is_long_running, debug = False,
595 show_output = False):
596
597 return FvpDriver.run(self, run_name, test_args, is_long_running,
598 debug, show_output)
J-Alves38223dd2021-04-20 17:31:48 +0100599
600 def finish(self):
601 """Clean up after running tests."""
J-Alves8d9fbb92021-12-13 17:28:15 +0000602 FvpDriver.finish(self)
J-Alves38223dd2021-04-20 17:31:48 +0100603
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000604class FvpDriverEL3SPMC(FvpDriverSPMC):
605 """
606 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
607 """
608
609 def __init__(self, args):
J-Alves19216692023-05-12 15:01:31 +0100610 FvpDriverSPMC.__init__(
611 self, args, cpu_start_address=0x04003000,
612 fvp_prebuilt_bl31=os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl31.bin"))
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000613 self.vms_in_partitions_json = args.partitions and args.partitions["SPs"]
J-Alves19216692023-05-12 15:01:31 +0100614 self._sp_dtb_address = 0x0403f000
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000615
616 def sp_partition_manifest_fvp_args(self):
617 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
618
619 # Expect only one tuple with img and load address, as EL3 SPMC only supports
620 # one SP.
621 assert(len(img_ldadd) == 1)
622 img, ldadd = img_ldadd[0]
623 fvp_args = ["--data", f"cluster0.cpu0={img}@{ldadd}"]
624
625 # Even though FF-A manifest is part of the SP PKG we need to load at a specific
626 # location. Fetch the respective dtb file and load at the following address.
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000627 output_path = os.path.dirname(os.path.dirname(img))
628 partition_manifest = f"{output_path}/partition-manifest.dtb"
J-Alves19216692023-05-12 15:01:31 +0100629 fvp_args += ["--data", f"cluster0.cpu0={partition_manifest}@{self._sp_dtb_address}"]
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000630 return fvp_args
631
632 def gen_fvp_args(
633 self, is_long_running, uart0_log_path, uart1_log_path, dt,
634 call_super = True, secure_ctrl = True, debug = False, show_output = False):
635 """Generate command line arguments for FVP."""
636 common_args = (self, is_long_running, uart0_log_path, uart1_log_path, dt.dtb,
637 debug, show_output)
638 fvp_args = FvpDriver.gen_fvp_args(*common_args) if call_super else []
639
640 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
641
642 fvp_args += self.sp_partition_manifest_fvp_args()
643
644 return fvp_args
645
Shruti Gupta22dbef32023-04-03 10:26:31 +0100646class FvpDriverEL3SPMCBothWorlds(FvpDriverHypervisor, FvpDriverEL3SPMC):
647 """
648 Driver which runs tests in Arm FVP emulator, with EL3 as SPMC
649 """
650
J-Alves19216692023-05-12 15:01:31 +0100651 def __init__(self, args):
652 FvpDriverHypervisor.__init__(self, args)
653 FvpDriverEL3SPMC.__init__(self, args)
Shruti Gupta22dbef32023-04-03 10:26:31 +0100654
J-Alves19216692023-05-12 15:01:31 +0100655 self._fvp_prebuilt_bl32 = os.path.join(FVP_PREBUILTS_TFA_EL3_SPMC_ROOT, "bl32.bin")
656 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 +0100657
658 def gen_fvp_args(
659 self, is_long_running, uart0_log_path, uart1_log_path, dt,
660 call_super = True, secure_ctrl = True, debug = False, show_output = False):
661 """Generate command line arguments for FVP."""
662
663 fvp_args = FvpDriverHypervisor.gen_fvp_args(self, is_long_running, uart0_log_path, uart1_log_path, dt,
664 debug, show_output)
665
666 fvp_args += FvpDriverSPMC.secure_ctrl_fvp_args(self, secure_ctrl)
667
668 if self.args.partitions is not None and self.args.partitions["SPs"] is not None:
669 fvp_args += FvpDriverEL3SPMC.sp_partition_manifest_fvp_args(self)
670 else :
671 # Use prebuilt TSP and TSP manifest if build does not specify SP
672 # EL3 SPMC expects SP to be loaded at 0xFF200000 and SP manifest at 0x0403F000
J-Alves19216692023-05-12 15:01:31 +0100673 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_bl32}@0xff200000"]
674 fvp_args += ["--data", f"cluster0.cpu0={self._fvp_prebuilt_dtb}@{self._sp_dtb_address}"]
Shruti Gupta22dbef32023-04-03 10:26:31 +0100675
676 return fvp_args
677
David Brazdil17e76652020-01-29 14:44:19 +0000678class SerialDriver(Driver):
679 """Driver which communicates with a device over the serial port."""
680
David Brazdil9d4ed962020-02-06 17:23:48 +0000681 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000682 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000683 self.tty_file = tty_file
684 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000685 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000686
David Brazdil9d4ed962020-02-06 17:23:48 +0000687 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000688 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000689
David Brazdil9d4ed962020-02-06 17:23:48 +0000690 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000691 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000692
David Brazdil17e76652020-01-29 14:44:19 +0000693 def run(self, run_name, test_args, is_long_running):
694 """Communicate `test_args` to the device over the serial port."""
695 run_state = self.start_run(run_name)
696
David Brazdil9d4ed962020-02-06 17:23:48 +0000697 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000698 with open(run_state.log_path, "a") as f:
699 while True:
700 # Read one line from the serial port.
701 line = ser.readline().decode('utf-8')
702 if len(line) == 0:
703 # Timeout
704 run_state.set_ret_code(124)
705 input("Timeout. " +
706 "Press ENTER and then reset the device...")
707 break
708 # Write the line to the log file.
709 f.write(line)
710 if HFTEST_CTRL_GET_COMMAND_LINE in line:
711 # Device is waiting for `test_args`.
712 ser.write(test_args.encode('ascii'))
713 ser.write(b'\r')
714 elif HFTEST_CTRL_FINISHED in line:
715 # Device has finished running this test and will reboot.
716 break
J-Alves18a25f92021-05-04 17:47:41 +0100717
David Brazdil17e76652020-01-29 14:44:19 +0000718 return self.finish_run(run_state)
719
David Brazdil94fd1e92020-02-03 16:45:20 +0000720 def finish(self):
721 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000722 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000723 while True:
724 line = ser.readline().decode('utf-8')
725 if len(line) == 0:
726 input("Timeout. Press ENTER and then reset the device...")
727 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
728 # Device is waiting for a command. Instruct it to exit
729 # the test environment.
730 ser.write("exit".encode('ascii'))
731 ser.write(b'\r')
732 break
733
David Brazdil2df24082019-09-05 11:55:08 +0100734# Tuple used to return information about the results of running a set of tests.
735TestRunnerResult = collections.namedtuple("TestRunnerResult", [
736 "tests_run",
737 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100738 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100739 ])
740
David Brazdil2df24082019-09-05 11:55:08 +0100741class TestRunner:
742 """Class which communicates with a test platform to obtain a list of
743 available tests and driving their execution."""
744
J-Alves8cc7dbb2021-04-16 10:38:48 +0100745 def __init__(self, artifacts, driver, test_set_up, suite_regex, test_regex,
J-Alves67c31912023-02-02 13:52:50 +0000746 skip_long_running_tests, force_long_running, debug, show_output):
David Brazdil2df24082019-09-05 11:55:08 +0100747 self.artifacts = artifacts
748 self.driver = driver
J-Alves8cc7dbb2021-04-16 10:38:48 +0100749 self.test_set_up = test_set_up
David Brazdil3cc24aa2019-09-27 10:24:41 +0100750 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100751 self.force_long_running = force_long_running
J-Alves67c31912023-02-02 13:52:50 +0000752 self.debug = debug
753 self.show_output = show_output
David Brazdil2df24082019-09-05 11:55:08 +0100754
755 self.suite_re = re.compile(suite_regex or ".*")
756 self.test_re = re.compile(test_regex or ".*")
757
758 def extract_hftest_lines(self, raw):
759 """Extract hftest-specific lines from a raw output from an invocation
760 of the test platform."""
761 lines = []
J-Alves07be7bb2021-04-13 11:09:12 +0100762 lines_to_process = raw.splitlines()
763
764 try:
765 # If logs have logs of more than one VM, the loop below to extract
766 # lines won't work. Thus, extracting between starting and ending
767 # logs: HFTEST_CTRL_GET_COMMAND_LINE and HFTEST_CTRL_FINISHED.
768 hftest_start = lines_to_process.index(HFTEST_CTRL_GET_COMMAND_LINE) + 1
769 hftest_end = lines_to_process.index(HFTEST_CTRL_FINISHED)
770 except ValueError:
771 hftest_start = 0
772 hftest_end = len(lines_to_process)
773
774 lines_to_process = lines_to_process[hftest_start : hftest_end]
775
776 for line in lines_to_process:
J-Alves3dbb8562020-12-01 10:45:37 +0000777 match = re.search(f"^VM \d+: ", line)
778 if match is not None:
779 line = line[match.end():]
David Brazdil2df24082019-09-05 11:55:08 +0100780 if line.startswith(HFTEST_LOG_PREFIX):
781 lines.append(line[len(HFTEST_LOG_PREFIX):])
782 return lines
783
784 def get_test_json(self):
785 """Invoke the test platform and request a JSON of available test and
786 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100787 out = self.driver.run("json", "json", self.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100788 hf_out = "\n".join(self.extract_hftest_lines(out))
789 try:
790 return json.loads(hf_out)
791 except ValueError as e:
792 print(out)
793 raise e
794
795 def collect_results(self, fn, it, xml_node):
796 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
797 Insert "tests" and "failures" nodes to `xml_node`."""
798 tests_run = 0
799 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100800 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100801 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100802 for i in it:
803 sub_result = fn(i)
804 assert(sub_result.tests_run >= sub_result.tests_failed)
805 tests_run += sub_result.tests_run
806 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100807 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100808 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100809
Andrew Walbranf9463922020-06-05 16:44:42 +0100810 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100811 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100812 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100813 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100814 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100815
816 def is_passed_test(self, test_out):
817 """Parse the output of a test and return True if it passed."""
818 return \
819 len(test_out) > 0 and \
820 test_out[-1] == HFTEST_LOG_FINISHED and \
821 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
822
Andrew Walbranf9463922020-06-05 16:44:42 +0100823 def get_failure_message(self, test_out):
824 """Parse the output of a test and return the message of the first
825 assertion failure."""
826 for i, line in enumerate(test_out):
827 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
828 # The assertion message is on the line after the 'Failure:'
829 return test_out[i + 1].strip()
830
831 return None
832
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000833 def get_log_name(self, suite, test):
834 """Returns a string with a generated log name for the test."""
835 log_name = ""
836
837 cpu = self.driver.args.cpu
838 if cpu:
839 log_name += cpu + "."
840
841 log_name += suite["name"] + "." + test["name"]
842
843 return log_name
844
David Brazdil2df24082019-09-05 11:55:08 +0100845 def run_test(self, suite, test, suite_xml):
846 """Invoke the test platform and request to run a given `test` in given
847 `suite`. Create a new XML node with results under `suite_xml`.
848 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100849 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100850 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100851
852 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100853 test_xml.set("name", test["name"])
854 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100855
J-Alvesd459b562022-12-05 14:56:33 +0000856 if (self.skip_long_running_tests and test["is_long_running"]) or test["skip_test"]:
Andrew Walbranf9463922020-06-05 16:44:42 +0100857 print(" SKIP", test["name"])
858 test_xml.set("status", "notrun")
859 skipped_xml = ET.SubElement(test_xml, "skipped")
860 skipped_xml.set("message", "Long running")
861 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
862
J-Alves67c31912023-02-02 13:52:50 +0000863 action_log = "DEBUG" if self.debug else "RUN"
864 print(f" {action_log}", test["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100865 log_name = self.get_log_name(suite, test)
866
David Brazdil2df24082019-09-05 11:55:08 +0100867 test_xml.set("status", "run")
868
Andrew Walbran42bf2842020-06-05 18:50:19 +0100869 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100870 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100871 log_name, "run {} {}".format(suite["name"], test["name"]),
J-Alves67c31912023-02-02 13:52:50 +0000872 test["is_long_running"] or self.force_long_running,
873 self.debug, self.show_output)
874
Andrew Walbranf9463922020-06-05 16:44:42 +0100875 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100876 elapsed_time = time.perf_counter() - start_time
877
878 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100879
Andrew Walbranf9463922020-06-05 16:44:42 +0100880 system_out_xml = ET.SubElement(test_xml, "system-out")
881 system_out_xml.text = out
882
883 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100884 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100885 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100886 else:
David Brazdil623b6812019-09-09 11:41:08 +0100887 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100888 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100889 failure_message = self.get_failure_message(hftest_out) or "Test failed"
890 failure_xml.set("message", failure_message)
891 failure_xml.text = '\n'.join(hftest_out)
892 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100893
894 def run_suite(self, suite, xml):
895 """Invoke the test platform and request to run all matching tests in
896 `suite`. Create new XML nodes with results under `xml`.
897 Suite skipped if it does not match the regex given to constructor."""
898 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100899 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100900
901 print(" SUITE", suite["name"])
902 suite_xml = ET.SubElement(xml, "testsuite")
903 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100904 properties_xml = ET.SubElement(suite_xml, "properties")
905
906 property_xml = ET.SubElement(properties_xml, "property")
907 property_xml.set("name", "driver")
908 property_xml.set("value", type(self.driver).__name__)
909
910 if self.driver.args.cpu:
911 property_xml = ET.SubElement(properties_xml, "property")
912 property_xml.set("name", "cpu")
913 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100914
915 return self.collect_results(
916 lambda test: self.run_test(suite, test, suite_xml),
917 suite["tests"],
918 suite_xml)
919
920 def run_tests(self):
921 """Run all suites and tests matching regexes given to constructor.
922 Write results to sponge log XML. Return the number of run and failed
923 tests."""
924
925 test_spec = self.get_test_json()
926 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
927
928 xml = ET.Element("testsuites")
J-Alves8cc7dbb2021-04-16 10:38:48 +0100929 xml.set("name", self.test_set_up)
David Brazdil2df24082019-09-05 11:55:08 +0100930 xml.set("timestamp", timestamp)
931
932 result = self.collect_results(
933 lambda suite: self.run_suite(suite, xml),
934 test_spec["suites"],
935 xml)
936
937 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000938 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
939 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100940
941 if result.tests_failed > 0:
942 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
943 "tests failed")
944 elif result.tests_run > 0:
945 print(" PASS: all", result.tests_run, "tests passed")
946
David Brazdil94fd1e92020-02-03 16:45:20 +0000947 # Let the driver clean up.
948 self.driver.finish()
949
David Brazdil2df24082019-09-05 11:55:08 +0100950 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100951
Andrew Scullbc7189d2018-08-14 09:35:13 +0100952def Main():
953 parser = argparse.ArgumentParser()
J-Alves8cc7dbb2021-04-16 10:38:48 +0100954 parser.add_argument("--hypervisor")
955 parser.add_argument("--spmc")
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000956 parser.add_argument("--el3_spmc", action="store_true")
Andrew Scull23e93a82018-10-26 14:56:04 +0100957 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100958 parser.add_argument("--out_initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100959 parser.add_argument("--out_partitions")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000960 parser.add_argument("--initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100961 parser.add_argument("--partitions_json")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100962 parser.add_argument("--suite")
963 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000964 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000965 parser.add_argument("--driver", default="qemu")
966 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
967 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000968 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100969 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100970 parser.add_argument("--force-long-running", action="store_true")
J-Alves67c31912023-02-02 13:52:50 +0000971 parser.add_argument("--debug", action="store_true",
972 help="Makes platforms stall waiting for debugger connection.")
973 parser.add_argument("--show-output", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000974 parser.add_argument("--cpu",
975 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000976 parser.add_argument("--tfa", action="store_true")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100977 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100978
J-Alves8cc7dbb2021-04-16 10:38:48 +0100979 # Create class which will manage all test artifacts.
980 if args.hypervisor and args.spmc:
981 test_set_up = "hypervisor_and_spmc"
982 elif args.hypervisor:
983 test_set_up = "hypervisor"
984 elif args.spmc:
985 test_set_up = "spmc"
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +0000986 elif args.el3_spmc:
987 test_set_up = "el3_spmc"
J-Alves8cc7dbb2021-04-16 10:38:48 +0100988 else:
989 raise Exception("No Hafnium image provided!\n")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100990
J-Alves8cc7dbb2021-04-16 10:38:48 +0100991 initrd = None
992 if args.hypervisor and args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100993 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
994 initrd = os.path.join(initrd_dir, "initrd.img")
J-Alves8cc7dbb2021-04-16 10:38:48 +0100995 test_set_up += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000996 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100997
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100998 partitions = None
J-Alves18a25f92021-05-04 17:47:41 +0100999 global_run_name = None
1000 if args.driver == "fvp":
1001 if args.partitions_json is not None:
1002 partitions_dir = os.path.join(
1003 args.out_partitions, "obj", args.partitions_json)
1004 partitions = json.load(open(partitions_dir, "r"))
1005 global_run_name = os.path.basename(args.partitions_json).split(".")[0]
1006 elif args.hypervisor:
1007 if args.initrd:
1008 global_run_name = os.path.basename(args.initrd)
1009 else:
1010 global_run_name = os.path.basename(args.hypervisor).split(".")[0]
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001011
David Brazdil2df24082019-09-05 11:55:08 +01001012 # Create class which will manage all test artifacts.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001013 log_dir = os.path.join(args.log, test_set_up)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001014 artifacts = ArtifactsManager(log_dir)
David Brazdil2df24082019-09-05 11:55:08 +01001015
1016 # Create a driver for the platform we want to test on.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001017 driver_args = DriverArgs(artifacts, args.hypervisor, args.spmc, initrd,
J-Alves18a25f92021-05-04 17:47:41 +01001018 vm_args, args.cpu, partitions, global_run_name)
David Brazdil17e76652020-01-29 14:44:19 +00001019
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001020 if args.el3_spmc:
J-Alves38223dd2021-04-20 17:31:48 +01001021 # So far only FVP supports tests for SPMC.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001022 if args.driver != "fvp":
1023 raise Exception("Secure tests can only run with fvp driver")
Shruti Gupta22dbef32023-04-03 10:26:31 +01001024 if args.hypervisor:
1025 driver = FvpDriverEL3SPMCBothWorlds(driver_args)
1026 else:
1027 driver = FvpDriverEL3SPMC(driver_args)
Shruti Gupta2b1e0cd2022-12-20 17:45:24 +00001028 elif args.spmc:
1029 # So far only FVP supports tests for SPMC.
1030 if args.driver != "fvp":
1031 raise Exception("Secure tests can only run with fvp driver")
J-Alves38223dd2021-04-20 17:31:48 +01001032 if args.hypervisor:
1033 driver = FvpDriverBothWorlds(driver_args)
1034 else:
1035 driver = FvpDriverSPMC(driver_args)
J-Alves8cc7dbb2021-04-16 10:38:48 +01001036 elif args.hypervisor:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001037 if args.driver == "qemu":
J-Alves8cc7dbb2021-04-16 10:38:48 +01001038 out = os.path.dirname(args.hypervisor)
1039 driver = QemuDriver(driver_args, out, args.tfa)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +01001040 elif args.driver == "fvp":
1041 driver = FvpDriverHypervisor(driver_args)
1042 elif args.driver == "serial":
1043 driver = SerialDriver(driver_args, args.serial_dev,
1044 args.serial_baudrate, not args.serial_no_init_wait)
1045 else:
1046 raise Exception("Unknown driver name: {}".format(args.driver))
J-Alves8cc7dbb2021-04-16 10:38:48 +01001047 else:
1048 raise Exception("No Hafnium image provided!\n")
David Brazdil2df24082019-09-05 11:55:08 +01001049
1050 # Create class which will drive test execution.
J-Alves8cc7dbb2021-04-16 10:38:48 +01001051 runner = TestRunner(artifacts, driver, test_set_up, args.suite, args.test,
J-Alves67c31912023-02-02 13:52:50 +00001052 args.skip_long_running_tests, args.force_long_running, args.debug, args.show_output)
David Brazdil2df24082019-09-05 11:55:08 +01001053
1054 # Run tests.
1055 runner_result = runner.run_tests()
1056
1057 # Print error message if no tests were run as this is probably unexpected.
1058 # Return suitable error code.
1059 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001060 print("Error: no tests match")
1061 return 10
David Brazdil2df24082019-09-05 11:55:08 +01001062 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +01001063 return 1
1064 else:
David Brazdil2df24082019-09-05 11:55:08 +01001065 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +01001066
1067if __name__ == "__main__":
1068 sys.exit(Main())