blob: e816e53e7682673d03da7667f3a3bd28b923eff4 [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
Andrew Scullbc7189d2018-08-14 09:35:13 +010029
Andrew Scull845fc9b2019-04-03 12:44:26 +010030HFTEST_LOG_PREFIX = "[hftest] "
31HFTEST_LOG_FAILURE_PREFIX = "Failure:"
32HFTEST_LOG_FINISHED = "FINISHED"
33
David Brazdil17e76652020-01-29 14:44:19 +000034HFTEST_CTRL_GET_COMMAND_LINE = "[hftest_ctrl:get_command_line]"
35HFTEST_CTRL_FINISHED = "[hftest_ctrl:finished]"
36
David Brazdil2df24082019-09-05 11:55:08 +010037HF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
38 os.path.abspath(__file__))))
David Brazdil5715f042019-08-27 11:11:51 +010039DTC_SCRIPT = os.path.join(HF_ROOT, "build", "image", "dtc.py")
David Brazdil2df24082019-09-05 11:55:08 +010040FVP_BINARY = os.path.join(
41 os.path.dirname(HF_ROOT), "fvp", "Base_RevC_AEMv8A_pkg", "models",
Olivier Depreze4153042020-10-02 15:24:59 +020042 "Linux64_GCC-6.4", "FVP_Base_RevC-2xAEMv8A")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010043HF_PREBUILTS = os.path.join(HF_ROOT, "prebuilts")
44FVP_PREBUILTS_TFA_TRUSTY_ROOT = os.path.join(
45 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-trusty", "fvp")
David Brazdil2df24082019-09-05 11:55:08 +010046FVP_PREBUILT_DTS = os.path.join(
Olivier Depreza6d2e6d2020-11-06 18:09:50 +010047 FVP_PREBUILTS_TFA_TRUSTY_ROOT, "fvp-base-gicv3-psci-1t.dts")
48
49FVP_PREBUILT_TFA_ROOT = os.path.join(
50 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a", "fvp")
Andrew Scull845fc9b2019-04-03 12:44:26 +010051
David Brazdil2df24082019-09-05 11:55:08 +010052def read_file(path):
53 with open(path, "r") as f:
54 return f.read()
Andrew Scull845fc9b2019-04-03 12:44:26 +010055
David Brazdil2df24082019-09-05 11:55:08 +010056def write_file(path, to_write, append=False):
57 with open(path, "a" if append else "w") as f:
58 f.write(to_write)
59
60def append_file(path, to_write):
61 write_file(path, to_write, append=True)
62
63def join_if_not_None(*args):
64 return " ".join(filter(lambda x: x, args))
65
66class ArtifactsManager:
67 """Class which manages folder with test artifacts."""
68
69 def __init__(self, log_dir):
70 self.created_files = []
71 self.log_dir = log_dir
72
73 # Create directory.
Andrew Scull845fc9b2019-04-03 12:44:26 +010074 try:
David Brazdil2df24082019-09-05 11:55:08 +010075 os.makedirs(self.log_dir)
76 except OSError:
77 if not os.path.isdir(self.log_dir):
78 raise
79 print("Logs saved under", log_dir)
80
81 # Create files expected by the Sponge test result parser.
82 self.sponge_log_path = self.create_file("sponge_log", ".log")
83 self.sponge_xml_path = self.create_file("sponge_log", ".xml")
84
David Brazdil623b6812019-09-09 11:41:08 +010085 def gen_file_path(self, basename, extension):
86 """Generate path to a file in the log directory."""
87 return os.path.join(self.log_dir, basename + extension)
88
David Brazdil2df24082019-09-05 11:55:08 +010089 def create_file(self, basename, extension):
90 """Create and touch a new file in the log folder. Ensure that no other
91 file of the same name was created by this instance of ArtifactsManager.
92 """
93 # Determine the path of the file.
David Brazdil623b6812019-09-09 11:41:08 +010094 path = self.gen_file_path(basename, extension)
David Brazdil2df24082019-09-05 11:55:08 +010095
96 # Check that the path is unique.
97 assert(path not in self.created_files)
98 self.created_files += [ path ]
99
100 # Touch file.
101 with open(path, "w") as f:
102 pass
103
104 return path
Andrew Scullbc7189d2018-08-14 09:35:13 +0100105
David Brazdil623b6812019-09-09 11:41:08 +0100106 def get_file(self, basename, extension):
107 """Return path to a file in the log folder. Assert that it was created
108 by this instance of ArtifactsManager."""
109 path = self.gen_file_path(basename, extension)
110 assert(path in self.created_files)
111 return path
112
Andrew Scullbc7189d2018-08-14 09:35:13 +0100113
David Brazdil2df24082019-09-05 11:55:08 +0100114# Tuple holding the arguments common to all driver constructors.
115# This is to avoid having to pass arguments from subclasses to superclasses.
116DriverArgs = collections.namedtuple("DriverArgs", [
117 "artifacts",
118 "kernel",
119 "initrd",
120 "vm_args",
David Brazdil17e76652020-01-29 14:44:19 +0000121 "cpu",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100122 "partitions"
David Brazdil2df24082019-09-05 11:55:08 +0100123 ])
Marc Bonnici0a125632019-04-01 13:46:52 +0100124
Andrew Walbran98656252019-03-14 14:52:29 +0000125
David Brazdil2df24082019-09-05 11:55:08 +0100126# State shared between the common Driver class and its subclasses during
127# a single invocation of the target platform.
David Brazdil7325eaf2019-09-27 13:04:51 +0100128class DriverRunState:
129 def __init__(self, log_path):
130 self.log_path = log_path
131 self.ret_code = 0
Andrew Walbran98656252019-03-14 14:52:29 +0000132
David Brazdil7325eaf2019-09-27 13:04:51 +0100133 def set_ret_code(self, ret_code):
134 self.ret_code = ret_code
Andrew Walbran98656252019-03-14 14:52:29 +0000135
David Brazdil0dbb41f2019-09-09 18:03:35 +0100136class DriverRunException(Exception):
137 """Exception thrown if subprocess invoked by a driver returned non-zero
138 status code. Used to fast-exit from a driver command sequence."""
139 pass
140
141
David Brazdil2df24082019-09-05 11:55:08 +0100142class Driver:
143 """Parent class of drivers for all testable platforms."""
144
145 def __init__(self, args):
146 self.args = args
147
David Brazdil623b6812019-09-09 11:41:08 +0100148 def get_run_log(self, run_name):
149 """Return path to the main log of a given test run."""
150 return self.args.artifacts.get_file(run_name, ".log")
151
David Brazdil2df24082019-09-05 11:55:08 +0100152 def start_run(self, run_name):
153 """Hook called by Driver subclasses before they invoke the target
154 platform."""
David Brazdil7325eaf2019-09-27 13:04:51 +0100155 return DriverRunState(self.args.artifacts.create_file(run_name, ".log"))
David Brazdil2df24082019-09-05 11:55:08 +0100156
Andrew Walbranf636b842020-01-10 11:46:12 +0000157 def exec_logged(self, run_state, exec_args, cwd=None):
David Brazdil2df24082019-09-05 11:55:08 +0100158 """Run a subprocess on behalf of a Driver subclass and append its
159 stdout and stderr to the main log."""
David Brazdil0dbb41f2019-09-09 18:03:35 +0100160 assert(run_state.ret_code == 0)
David Brazdil2df24082019-09-05 11:55:08 +0100161 with open(run_state.log_path, "a") as f:
162 f.write("$ {}\r\n".format(" ".join(exec_args)))
163 f.flush()
Andrew Walbranf636b842020-01-10 11:46:12 +0000164 ret_code = subprocess.call(exec_args, stdout=f, stderr=f, cwd=cwd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100165 if ret_code != 0:
David Brazdil7325eaf2019-09-27 13:04:51 +0100166 run_state.set_ret_code(ret_code)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100167 raise DriverRunException()
David Brazdil2df24082019-09-05 11:55:08 +0100168
David Brazdil0dbb41f2019-09-09 18:03:35 +0100169 def finish_run(self, run_state):
David Brazdil2df24082019-09-05 11:55:08 +0100170 """Hook called by Driver subclasses after they finished running the
171 target platform. `ret_code` argument is the return code of the main
172 command run by the driver. A corresponding log message is printed."""
173 # Decode return code and add a message to the log.
174 with open(run_state.log_path, "a") as f:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100175 if run_state.ret_code == 124:
David Brazdil2df24082019-09-05 11:55:08 +0100176 f.write("\r\n{}{} timed out\r\n".format(
177 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100178 elif run_state.ret_code != 0:
David Brazdil2df24082019-09-05 11:55:08 +0100179 f.write("\r\n{}{} process return code {}\r\n".format(
David Brazdil0dbb41f2019-09-09 18:03:35 +0100180 HFTEST_LOG_PREFIX, HFTEST_LOG_FAILURE_PREFIX,
181 run_state.ret_code))
David Brazdil2df24082019-09-05 11:55:08 +0100182
183 # Append log of this run to full test log.
184 log_content = read_file(run_state.log_path)
185 append_file(
186 self.args.artifacts.sponge_log_path,
187 log_content + "\r\n\r\n")
188 return log_content
Andrew Walbran98656252019-03-14 14:52:29 +0000189
190
David Brazdil2df24082019-09-05 11:55:08 +0100191class QemuDriver(Driver):
192 """Driver which runs tests in QEMU."""
193
Andrew Walbranf636b842020-01-10 11:46:12 +0000194 def __init__(self, args, qemu_wd, tfa):
David Brazdil2df24082019-09-05 11:55:08 +0100195 Driver.__init__(self, args)
Andrew Walbranf636b842020-01-10 11:46:12 +0000196 self.qemu_wd = qemu_wd
197 self.tfa = tfa
David Brazdil2df24082019-09-05 11:55:08 +0100198
David Brazdila2358d42020-01-27 18:51:38 +0000199 def gen_exec_args(self, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100200 """Generate command line arguments for QEMU."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100201 time_limit = "120s" if is_long_running else "10s"
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000202 # If no CPU configuration is selected, then test against the maximum
203 # configuration, "max", supported by QEMU.
204 cpu = self.args.cpu or "max"
David Brazdil2df24082019-09-05 11:55:08 +0100205 exec_args = [
David Brazdil3cc24aa2019-09-27 10:24:41 +0100206 "timeout", "--foreground", time_limit,
Andrew Walbranf636b842020-01-10 11:46:12 +0000207 os.path.abspath("prebuilts/linux-x64/qemu/qemu-system-aarch64"),
Andrew Walbrana081a292020-01-23 10:08:42 +0000208 "-machine", "virt,virtualization=on,gic-version=3",
Andrew Walbranf636b842020-01-10 11:46:12 +0000209 "-cpu", cpu, "-smp", "4", "-m", "1G",
David Brazdil2df24082019-09-05 11:55:08 +0100210 "-nographic", "-nodefaults", "-serial", "stdio",
Andrew Walbranf636b842020-01-10 11:46:12 +0000211 "-d", "unimp", "-kernel", os.path.abspath(self.args.kernel),
David Brazdil2df24082019-09-05 11:55:08 +0100212 ]
213
Andrew Walbranf636b842020-01-10 11:46:12 +0000214 if self.tfa:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100215 bl1_path = os.path.join(
216 HF_PREBUILTS, "linux-aarch64", "trusted-firmware-a-trusty",
217 "qemu", "bl1.bin")
Andrew Walbranf636b842020-01-10 11:46:12 +0000218 exec_args += ["-bios",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100219 os.path.abspath(bl1_path),
220 "-machine", "secure=on", "-semihosting-config",
Andrew Walbranf636b842020-01-10 11:46:12 +0000221 "enable,target=native"]
222
David Brazdil2df24082019-09-05 11:55:08 +0100223 if self.args.initrd:
Andrew Walbranf636b842020-01-10 11:46:12 +0000224 exec_args += ["-initrd", os.path.abspath(self.args.initrd)]
David Brazdil2df24082019-09-05 11:55:08 +0100225
226 vm_args = join_if_not_None(self.args.vm_args, test_args)
227 if vm_args:
228 exec_args += ["-append", vm_args]
229
230 return exec_args
231
David Brazdil3cc24aa2019-09-27 10:24:41 +0100232 def run(self, run_name, test_args, is_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100233 """Run test given by `test_args` in QEMU."""
234 run_state = self.start_run(run_name)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100235
236 try:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100237 # Execute test in QEMU..
David Brazdila2358d42020-01-27 18:51:38 +0000238 exec_args = self.gen_exec_args(test_args, is_long_running)
Andrew Walbranf636b842020-01-10 11:46:12 +0000239 self.exec_logged(run_state, exec_args,
240 cwd=self.qemu_wd)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100241 except DriverRunException:
242 pass
243
244 return self.finish_run(run_state)
Andrew Scullbc7189d2018-08-14 09:35:13 +0100245
David Brazdil94fd1e92020-02-03 16:45:20 +0000246 def finish(self):
247 """Clean up after running tests."""
248 pass
249
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100250class FvpDriver(Driver, ABC):
251 """Base class for driver which runs tests in Arm FVP emulator."""
David Brazdil2df24082019-09-05 11:55:08 +0100252
253 def __init__(self, args):
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000254 if args.cpu:
255 raise ValueError("FVP emulator does not support the --cpu option.")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100256 super().__init__(args)
David Brazdil2df24082019-09-05 11:55:08 +0100257
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100258 @property
259 @abstractmethod
260 def CPU_START_ADDRESS(self):
261 pass
David Brazdil2df24082019-09-05 11:55:08 +0100262
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100263 @property
264 @abstractmethod
265 def DTB_ADDRESS(self):
266 pass
267
268 @property
269 @abstractmethod
270 def FVP_PREBUILT_BL31(self):
271 pass
272
273 @property
274 @abstractmethod
275 def KERNEL_ADDRESS(self):
276 pass
277
278 def create_dt(self, run_name : str):
279 """Create DT related files, and return respective paths in a tuple
280 (dts,dtb)"""
281 return self.args.artifacts.create_file(run_name, ".dts"), \
282 self.args.artifacts.create_file(run_name, ".dtb")
283
284 def compile_dt(self, run_state, dts_path, dtb_path):
285 """Compile DT calling dtc."""
286 dtc_args = [
287 DTC_SCRIPT, "compile", "-i", dts_path, "-o", dtb_path,
288 ]
289 self.exec_logged(run_state, dtc_args)
290
291 def create_uart_log(self, run_name : str, file_name : str):
292 """Create uart log file, and return path"""
293 return self.args.artifacts.create_file(run_name, file_name)
294
295 def get_img_and_ldadd(self, partitions : dict):
296 ret = []
297 for i, p in enumerate(partitions):
298 with open(p["dts"], "r") as dts:
299 manifest = fdt.parse_dts(dts.read())
300 load_address = manifest.get_property("load_address",
301 f"/hypervisor/vm{str(i+1)}").value
302 ret.append((p["img"], load_address))
303 return ret
304
305 def get_manifests_from_json(self, partitions : list):
306 manifests = ""
307 if partitions is not None:
308 for p in partitions:
309 manifests += read_file(p["dts"])
310 return manifests
311
312 @abstractmethod
313 def gen_dts(self, dts_path, test_args):
314 """Abstract method to generate dts file. This specific to the use case
315 so should be implemented within derived driver"""
316 pass
317
318 @abstractmethod
David Brazdil2df24082019-09-05 11:55:08 +0100319 def gen_fvp_args(
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100320 self, is_long_running, uart0_log_path, uart1_log_path, dtb_path):
David Brazdil2df24082019-09-05 11:55:08 +0100321 """Generate command line arguments for FVP."""
Andrew Walbranee5418e2019-11-27 17:43:05 +0000322 time_limit = "80s" if is_long_running else "40s"
David Brazdil2df24082019-09-05 11:55:08 +0100323 fvp_args = [
Andrew Walbranee5418e2019-11-27 17:43:05 +0000324 "timeout", "--foreground", time_limit,
David Brazdil2df24082019-09-05 11:55:08 +0100325 FVP_BINARY,
326 "-C", "pctl.startup=0.0.0.0",
327 "-C", "bp.secure_memory=0",
328 "-C", "cluster0.NUM_CORES=4",
329 "-C", "cluster1.NUM_CORES=4",
330 "-C", "cache_state_modelled=0",
331 "-C", "bp.vis.disable_visualisation=true",
332 "-C", "bp.vis.rate_limit-enable=false",
333 "-C", "bp.terminal_0.start_telnet=false",
334 "-C", "bp.terminal_1.start_telnet=false",
335 "-C", "bp.terminal_2.start_telnet=false",
336 "-C", "bp.terminal_3.start_telnet=false",
337 "-C", "bp.pl011_uart0.untimed_fifos=1",
338 "-C", "bp.pl011_uart0.unbuffered_output=1",
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100339 "-C", f"bp.pl011_uart0.out_file={uart0_log_path}",
340 "-C", f"bp.pl011_uart1.out_file={uart1_log_path}",
341 "-C", f"cluster0.cpu0.RVBAR={self.CPU_START_ADDRESS}",
342 "-C", f"cluster0.cpu1.RVBAR={self.CPU_START_ADDRESS}",
343 "-C", f"cluster0.cpu2.RVBAR={self.CPU_START_ADDRESS}",
344 "-C", f"cluster0.cpu3.RVBAR={self.CPU_START_ADDRESS}",
345 "-C", f"cluster1.cpu0.RVBAR={self.CPU_START_ADDRESS}",
346 "-C", f"cluster1.cpu1.RVBAR={self.CPU_START_ADDRESS}",
347 "-C", f"cluster1.cpu2.RVBAR={self.CPU_START_ADDRESS}",
348 "-C", f"cluster1.cpu3.RVBAR={self.CPU_START_ADDRESS}",
349 "--data",
350 f"cluster0.cpu0={self.FVP_PREBUILT_BL31}@{self.CPU_START_ADDRESS}",
351 "--data", f"cluster0.cpu0={dtb_path}@{self.DTB_ADDRESS}",
352 "--data", f"cluster0.cpu0={self.args.kernel}@{self.KERNEL_ADDRESS}",
David Brazdil2df24082019-09-05 11:55:08 +0100353 "-C", "bp.ve_sysregs.mmbSiteDefault=0",
354 "-C", "bp.ve_sysregs.exit_on_shutdown=1",
355 ]
David Brazdil2df24082019-09-05 11:55:08 +0100356 return fvp_args
357
David Brazdil3cc24aa2019-09-27 10:24:41 +0100358 def run(self, run_name, test_args, is_long_running):
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100359 """ Run test """
David Brazdil2df24082019-09-05 11:55:08 +0100360 run_state = self.start_run(run_name)
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100361 dts_path, dtb_path = self.create_dt(run_name)
362 uart0_log_path = self.create_uart_log(run_name, ".uart0.log")
363 uart1_log_path = self.create_uart_log(run_name, ".uart1.log")
David Brazdil2df24082019-09-05 11:55:08 +0100364
David Brazdil0dbb41f2019-09-09 18:03:35 +0100365 try:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100366 self.gen_dts(dts_path, test_args)
367 self.compile_dt(run_state, dts_path, dtb_path)
368 fvp_args = self.gen_fvp_args(is_long_running, uart0_log_path,
369 uart1_log_path, dtb_path)
David Brazdil0dbb41f2019-09-09 18:03:35 +0100370 self.exec_logged(run_state, fvp_args)
371 except DriverRunException:
372 pass
David Brazdil2df24082019-09-05 11:55:08 +0100373
374 # Append UART0 output to main log.
375 append_file(run_state.log_path, read_file(uart0_log_path))
David Brazdil0dbb41f2019-09-09 18:03:35 +0100376 return self.finish_run(run_state)
David Brazdil2df24082019-09-05 11:55:08 +0100377
David Brazdil94fd1e92020-02-03 16:45:20 +0000378 def finish(self):
379 """Clean up after running tests."""
380 pass
381
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100382class FvpDriverHypervisor(FvpDriver):
383 """
384 Driver which runs tests in Arm FVP emulator, with hafnium as hypervisor
385 """
386 INITRD_START= 0x84000000
387 INITRD_END = 0x85000000 #Default value, however may change if initrd in args
388
389 def __init__(self, args):
390 self.vms_in_partitions_json = args.partitions and args.partitions["VMs"]
391 super().__init__(args)
392
393 @property
394 def CPU_START_ADDRESS(self):
395 return "0x04020000"
396
397 @property
398 def DTB_ADDRESS(self):
399 return "0x82000000"
400
401 @property
402 def FVP_PREBUILT_BL31(self):
403 return os.path.join(FVP_PREBUILTS_TFA_TRUSTY_ROOT, "bl31.bin")
404
405 @property
406 def KERNEL_ADDRESS(self):
407 return "0x80000000"
408
409 def gen_dts(self, dts_path, test_args):
410 """Create a DeviceTree source which will be compiled into a DTB and
411 passed to FVP for a test run."""
412
413 vm_args = join_if_not_None(self.args.vm_args, test_args)
414 write_file(dts_path, read_file(FVP_PREBUILT_DTS))
415
416 # Write the vm arguments to the partition manifest
417 to_append = f"""
418/ {{
419 chosen {{
420 bootargs = "{vm_args}";
421 stdout-path = "serial0:115200n8";
422 linux,initrd-start = <{self.INITRD_START if self.args.initrd else 0}>;
423 linux,initrd-end = <{self.INITRD_END if self.args.initrd else 0}>;
424 }};
425}};"""
426 if self.vms_in_partitions_json:
427 to_append += self.get_manifests_from_json(self.args.partitions["VMs"])
428
429 append_file(dts_path, to_append)
430
431 def gen_fvp_args(
432 self, is_long_running, uart0_log_path, uart1_log_path, dtb_path):
433 """Generate command line arguments for FVP."""
434
435 fvp_args = super().gen_fvp_args(
436 is_long_running, uart0_log_path, uart1_log_path, dtb_path)
437
438 if self.vms_in_partitions_json:
439 img_ldadd = self.get_img_and_ldadd(self.args.partitions["VMs"])
440 for img, ldadd in img_ldadd:
441 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
442
443 if self.args.initrd:
444 fvp_args += [
445 "--data",
446 f"cluster0.cpu0={self.args.initrd}@{self.INITRD_START}"
447 ]
448 return fvp_args
449
450class FvpDriverSPMC(FvpDriver):
451 """
452 Driver which runs tests in Arm FVP emulator, with hafnium as SPMC
453 """
454 FVP_PREBUILT_SECURE_DTS = os.path.join(
455 HF_ROOT, "test", "vmapi", "fvp-base-spmc.dts")
456 HFTEST_CMD_FILE = os.path.join("/tmp/", "hftest_cmds")
457
458 def __init__(self, args):
459 if args.partitions is None or args.partitions["SPs"] is None:
460 raise Exception("Need to specify provide SPs in partitions_json")
461 super().__init__(args)
462
463 @property
464 def CPU_START_ADDRESS(self):
465 return "0x04010000"
466
467 @property
468 def DTB_ADDRESS(self):
469 return "0x0403f000"
470
471 @property
472 def FVP_PREBUILT_BL31(self):
473 return os.path.join(FVP_PREBUILT_TFA_ROOT, "bl31_spmd.bin")
474
475 @property
476 def KERNEL_ADDRESS(self):
477 return "0x6000000"
478
479 def gen_dts(self, dts_path, test_args):
480 """Create a DeviceTree source which will be compiled into a DTB and
481 passed to FVP for a test run."""
482 to_append = self.get_manifests_from_json(self.args.partitions["SPs"])
483 write_file(dts_path, read_file(FvpDriverSPMC.FVP_PREBUILT_SECURE_DTS))
484 append_file(dts_path, to_append)
485
486 def gen_fvp_args(
487 self, is_long_running, uart0_log_path, uart1_log_path, dtb_path):
488 """Generate command line arguments for FVP."""
489 fvp_args = super().gen_fvp_args(
490 is_long_running, uart0_log_path, uart1_log_path, dtb_path)
491 fvp_args += [
492 "-C", f"bp.pl011_uart0.in_file={FvpDriverSPMC.HFTEST_CMD_FILE}",
493 "-C", f"bp.pl011_uart0.shutdown_tag=\"{HFTEST_CTRL_FINISHED}\"",
494 "-C", "cluster0.has_arm_v8-4=1",
495 "-C", "cluster1.has_arm_v8-4=1",
496 ]
497 img_ldadd = self.get_img_and_ldadd(self.args.partitions["SPs"])
498 for img, ldadd in img_ldadd:
499 fvp_args += ["--data", f"cluster0.cpu0={img}@{hex(ldadd)}"]
500
501 return fvp_args
502
503 def run(self, run_name, test_args, is_long_running):
504 with open(FvpDriverSPMC.HFTEST_CMD_FILE, "w+") as f:
505 vm_args = join_if_not_None(self.args.vm_args, test_args)
506 f.write(f"{vm_args}\n")
507 return super().run(run_name, test_args, is_long_running)
508
509 def finish(self):
510 """Clean up after running tests."""
511 os.remove(FvpDriverSPMC.HFTEST_CMD_FILE)
David Brazdil2df24082019-09-05 11:55:08 +0100512
David Brazdil17e76652020-01-29 14:44:19 +0000513class SerialDriver(Driver):
514 """Driver which communicates with a device over the serial port."""
515
David Brazdil9d4ed962020-02-06 17:23:48 +0000516 def __init__(self, args, tty_file, baudrate, init_wait):
David Brazdil17e76652020-01-29 14:44:19 +0000517 Driver.__init__(self, args)
David Brazdil9d4ed962020-02-06 17:23:48 +0000518 self.tty_file = tty_file
519 self.baudrate = baudrate
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000520 self.pyserial = importlib.import_module("serial")
David Brazdild8013f92020-02-03 16:40:25 +0000521
David Brazdil9d4ed962020-02-06 17:23:48 +0000522 if init_wait:
David Brazdild8013f92020-02-03 16:40:25 +0000523 input("Press ENTER and then reset the device...")
David Brazdil17e76652020-01-29 14:44:19 +0000524
David Brazdil9d4ed962020-02-06 17:23:48 +0000525 def connect(self):
David Brazdil4f9cf9a2020-02-06 17:34:44 +0000526 return self.pyserial.Serial(self.tty_file, self.baudrate, timeout=10)
David Brazdil9d4ed962020-02-06 17:23:48 +0000527
David Brazdil17e76652020-01-29 14:44:19 +0000528 def run(self, run_name, test_args, is_long_running):
529 """Communicate `test_args` to the device over the serial port."""
530 run_state = self.start_run(run_name)
531
David Brazdil9d4ed962020-02-06 17:23:48 +0000532 with self.connect() as ser:
David Brazdil17e76652020-01-29 14:44:19 +0000533 with open(run_state.log_path, "a") as f:
534 while True:
535 # Read one line from the serial port.
536 line = ser.readline().decode('utf-8')
537 if len(line) == 0:
538 # Timeout
539 run_state.set_ret_code(124)
540 input("Timeout. " +
541 "Press ENTER and then reset the device...")
542 break
543 # Write the line to the log file.
544 f.write(line)
545 if HFTEST_CTRL_GET_COMMAND_LINE in line:
546 # Device is waiting for `test_args`.
547 ser.write(test_args.encode('ascii'))
548 ser.write(b'\r')
549 elif HFTEST_CTRL_FINISHED in line:
550 # Device has finished running this test and will reboot.
551 break
552 return self.finish_run(run_state)
553
David Brazdil94fd1e92020-02-03 16:45:20 +0000554 def finish(self):
555 """Clean up after running tests."""
David Brazdil9d4ed962020-02-06 17:23:48 +0000556 with self.connect() as ser:
David Brazdil94fd1e92020-02-03 16:45:20 +0000557 while True:
558 line = ser.readline().decode('utf-8')
559 if len(line) == 0:
560 input("Timeout. Press ENTER and then reset the device...")
561 elif HFTEST_CTRL_GET_COMMAND_LINE in line:
562 # Device is waiting for a command. Instruct it to exit
563 # the test environment.
564 ser.write("exit".encode('ascii'))
565 ser.write(b'\r')
566 break
567
David Brazdil17e76652020-01-29 14:44:19 +0000568
David Brazdil2df24082019-09-05 11:55:08 +0100569# Tuple used to return information about the results of running a set of tests.
570TestRunnerResult = collections.namedtuple("TestRunnerResult", [
571 "tests_run",
572 "tests_failed",
Andrew Walbranf9463922020-06-05 16:44:42 +0100573 "tests_skipped",
David Brazdil2df24082019-09-05 11:55:08 +0100574 ])
575
576
577class TestRunner:
578 """Class which communicates with a test platform to obtain a list of
579 available tests and driving their execution."""
580
David Brazdil3cc24aa2019-09-27 10:24:41 +0100581 def __init__(self, artifacts, driver, image_name, suite_regex, test_regex,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100582 skip_long_running_tests, force_long_running):
David Brazdil2df24082019-09-05 11:55:08 +0100583 self.artifacts = artifacts
584 self.driver = driver
585 self.image_name = image_name
David Brazdil3cc24aa2019-09-27 10:24:41 +0100586 self.skip_long_running_tests = skip_long_running_tests
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100587 self.force_long_running = force_long_running
David Brazdil2df24082019-09-05 11:55:08 +0100588
589 self.suite_re = re.compile(suite_regex or ".*")
590 self.test_re = re.compile(test_regex or ".*")
591
592 def extract_hftest_lines(self, raw):
593 """Extract hftest-specific lines from a raw output from an invocation
594 of the test platform."""
595 lines = []
596 for line in raw.splitlines():
J-Alves3dbb8562020-12-01 10:45:37 +0000597 match = re.search(f"^VM \d+: ", line)
598 if match is not None:
599 line = line[match.end():]
David Brazdil2df24082019-09-05 11:55:08 +0100600 if line.startswith(HFTEST_LOG_PREFIX):
601 lines.append(line[len(HFTEST_LOG_PREFIX):])
602 return lines
603
604 def get_test_json(self):
605 """Invoke the test platform and request a JSON of available test and
606 test suites."""
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100607 out = self.driver.run("json", "json", self.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100608 hf_out = "\n".join(self.extract_hftest_lines(out))
609 try:
610 return json.loads(hf_out)
611 except ValueError as e:
612 print(out)
613 raise e
614
615 def collect_results(self, fn, it, xml_node):
616 """Run `fn` on every entry in `it` and collect their TestRunnerResults.
617 Insert "tests" and "failures" nodes to `xml_node`."""
618 tests_run = 0
619 tests_failed = 0
Andrew Walbranf9463922020-06-05 16:44:42 +0100620 tests_skipped = 0
Andrew Walbran42bf2842020-06-05 18:50:19 +0100621 start_time = time.perf_counter()
David Brazdil2df24082019-09-05 11:55:08 +0100622 for i in it:
623 sub_result = fn(i)
624 assert(sub_result.tests_run >= sub_result.tests_failed)
625 tests_run += sub_result.tests_run
626 tests_failed += sub_result.tests_failed
Andrew Walbranf9463922020-06-05 16:44:42 +0100627 tests_skipped += sub_result.tests_skipped
Andrew Walbran42bf2842020-06-05 18:50:19 +0100628 elapsed_time = time.perf_counter() - start_time
David Brazdil2df24082019-09-05 11:55:08 +0100629
Andrew Walbranf9463922020-06-05 16:44:42 +0100630 xml_node.set("tests", str(tests_run + tests_skipped))
David Brazdil2df24082019-09-05 11:55:08 +0100631 xml_node.set("failures", str(tests_failed))
Andrew Walbranf9463922020-06-05 16:44:42 +0100632 xml_node.set("skipped", str(tests_skipped))
Andrew Walbran42bf2842020-06-05 18:50:19 +0100633 xml_node.set("time", str(elapsed_time))
Andrew Walbranf9463922020-06-05 16:44:42 +0100634 return TestRunnerResult(tests_run, tests_failed, tests_skipped)
David Brazdil2df24082019-09-05 11:55:08 +0100635
636 def is_passed_test(self, test_out):
637 """Parse the output of a test and return True if it passed."""
638 return \
639 len(test_out) > 0 and \
640 test_out[-1] == HFTEST_LOG_FINISHED and \
641 not any(l.startswith(HFTEST_LOG_FAILURE_PREFIX) for l in test_out)
642
Andrew Walbranf9463922020-06-05 16:44:42 +0100643 def get_failure_message(self, test_out):
644 """Parse the output of a test and return the message of the first
645 assertion failure."""
646 for i, line in enumerate(test_out):
647 if line.startswith(HFTEST_LOG_FAILURE_PREFIX) and i + 1 < len(test_out):
648 # The assertion message is on the line after the 'Failure:'
649 return test_out[i + 1].strip()
650
651 return None
652
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000653 def get_log_name(self, suite, test):
654 """Returns a string with a generated log name for the test."""
655 log_name = ""
656
657 cpu = self.driver.args.cpu
658 if cpu:
659 log_name += cpu + "."
660
661 log_name += suite["name"] + "." + test["name"]
662
663 return log_name
664
David Brazdil2df24082019-09-05 11:55:08 +0100665 def run_test(self, suite, test, suite_xml):
666 """Invoke the test platform and request to run a given `test` in given
667 `suite`. Create a new XML node with results under `suite_xml`.
668 Test only invoked if it matches the regex given to constructor."""
David Brazdil3cc24aa2019-09-27 10:24:41 +0100669 if not self.test_re.match(test["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100670 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100671
672 test_xml = ET.SubElement(suite_xml, "testcase")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100673 test_xml.set("name", test["name"])
674 test_xml.set("classname", suite["name"])
Andrew Walbranf9463922020-06-05 16:44:42 +0100675
676 if self.skip_long_running_tests and test["is_long_running"]:
677 print(" SKIP", test["name"])
678 test_xml.set("status", "notrun")
679 skipped_xml = ET.SubElement(test_xml, "skipped")
680 skipped_xml.set("message", "Long running")
681 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=1)
682
683 print(" RUN", test["name"])
684 log_name = self.get_log_name(suite, test)
685
David Brazdil2df24082019-09-05 11:55:08 +0100686 test_xml.set("status", "run")
687
Andrew Walbran42bf2842020-06-05 18:50:19 +0100688 start_time = time.perf_counter()
Andrew Walbranf9463922020-06-05 16:44:42 +0100689 out = self.driver.run(
David Brazdil3cc24aa2019-09-27 10:24:41 +0100690 log_name, "run {} {}".format(suite["name"], test["name"]),
Andrew Walbranf9463922020-06-05 16:44:42 +0100691 test["is_long_running"] or self.force_long_running)
692 hftest_out = self.extract_hftest_lines(out)
Andrew Walbran42bf2842020-06-05 18:50:19 +0100693 elapsed_time = time.perf_counter() - start_time
694
695 test_xml.set("time", str(elapsed_time))
David Brazdil2df24082019-09-05 11:55:08 +0100696
Andrew Walbranf9463922020-06-05 16:44:42 +0100697 system_out_xml = ET.SubElement(test_xml, "system-out")
698 system_out_xml.text = out
699
700 if self.is_passed_test(hftest_out):
David Brazdil2df24082019-09-05 11:55:08 +0100701 print(" PASS")
Andrew Walbranf9463922020-06-05 16:44:42 +0100702 return TestRunnerResult(tests_run=1, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100703 else:
David Brazdil623b6812019-09-09 11:41:08 +0100704 print("[x] FAIL --", self.driver.get_run_log(log_name))
David Brazdil2df24082019-09-05 11:55:08 +0100705 failure_xml = ET.SubElement(test_xml, "failure")
Andrew Walbranf9463922020-06-05 16:44:42 +0100706 failure_message = self.get_failure_message(hftest_out) or "Test failed"
707 failure_xml.set("message", failure_message)
708 failure_xml.text = '\n'.join(hftest_out)
709 return TestRunnerResult(tests_run=1, tests_failed=1, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100710
711 def run_suite(self, suite, xml):
712 """Invoke the test platform and request to run all matching tests in
713 `suite`. Create new XML nodes with results under `xml`.
714 Suite skipped if it does not match the regex given to constructor."""
715 if not self.suite_re.match(suite["name"]):
Andrew Walbranf9463922020-06-05 16:44:42 +0100716 return TestRunnerResult(tests_run=0, tests_failed=0, tests_skipped=0)
David Brazdil2df24082019-09-05 11:55:08 +0100717
718 print(" SUITE", suite["name"])
719 suite_xml = ET.SubElement(xml, "testsuite")
720 suite_xml.set("name", suite["name"])
Andrew Walbran16ae62e2020-06-05 18:27:46 +0100721 properties_xml = ET.SubElement(suite_xml, "properties")
722
723 property_xml = ET.SubElement(properties_xml, "property")
724 property_xml.set("name", "driver")
725 property_xml.set("value", type(self.driver).__name__)
726
727 if self.driver.args.cpu:
728 property_xml = ET.SubElement(properties_xml, "property")
729 property_xml.set("name", "cpu")
730 property_xml.set("value", self.driver.args.cpu)
David Brazdil2df24082019-09-05 11:55:08 +0100731
732 return self.collect_results(
733 lambda test: self.run_test(suite, test, suite_xml),
734 suite["tests"],
735 suite_xml)
736
737 def run_tests(self):
738 """Run all suites and tests matching regexes given to constructor.
739 Write results to sponge log XML. Return the number of run and failed
740 tests."""
741
742 test_spec = self.get_test_json()
743 timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
744
745 xml = ET.Element("testsuites")
746 xml.set("name", self.image_name)
747 xml.set("timestamp", timestamp)
748
749 result = self.collect_results(
750 lambda suite: self.run_suite(suite, xml),
751 test_spec["suites"],
752 xml)
753
754 # Write XML to file.
David Brazdilee5e25d2020-01-24 14:17:45 +0000755 ET.ElementTree(xml).write(self.artifacts.sponge_xml_path,
756 encoding='utf-8', xml_declaration=True)
David Brazdil2df24082019-09-05 11:55:08 +0100757
758 if result.tests_failed > 0:
759 print("[x] FAIL:", result.tests_failed, "of", result.tests_run,
760 "tests failed")
761 elif result.tests_run > 0:
762 print(" PASS: all", result.tests_run, "tests passed")
763
David Brazdil94fd1e92020-02-03 16:45:20 +0000764 # Let the driver clean up.
765 self.driver.finish()
766
David Brazdil2df24082019-09-05 11:55:08 +0100767 return result
Andrew Scullbc7189d2018-08-14 09:35:13 +0100768
Andrew Scullbc7189d2018-08-14 09:35:13 +0100769def Main():
770 parser = argparse.ArgumentParser()
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000771 parser.add_argument("image")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100772 parser.add_argument("--out", required=True)
Andrew Scull23e93a82018-10-26 14:56:04 +0100773 parser.add_argument("--log", required=True)
Andrew Walbran7559fcf2019-05-09 17:11:20 +0100774 parser.add_argument("--out_initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100775 parser.add_argument("--out_partitions")
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000776 parser.add_argument("--initrd")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100777 parser.add_argument("--partitions_json")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100778 parser.add_argument("--suite")
779 parser.add_argument("--test")
Andrew Walbranbc342d42019-02-05 16:56:02 +0000780 parser.add_argument("--vm_args")
David Brazdil17e76652020-01-29 14:44:19 +0000781 parser.add_argument("--driver", default="qemu")
782 parser.add_argument("--serial-dev", default="/dev/ttyUSB0")
783 parser.add_argument("--serial-baudrate", type=int, default=115200)
David Brazdild8013f92020-02-03 16:40:25 +0000784 parser.add_argument("--serial-no-init-wait", action="store_true")
David Brazdil3cc24aa2019-09-27 10:24:41 +0100785 parser.add_argument("--skip-long-running-tests", action="store_true")
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100786 parser.add_argument("--force-long-running", action="store_true")
Fuad Tabba36c8c2b2019-11-04 16:55:32 +0000787 parser.add_argument("--cpu",
788 help="Selects the CPU configuration for the run environment.")
Andrew Walbranf636b842020-01-10 11:46:12 +0000789 parser.add_argument("--tfa", action="store_true")
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100790 parser.add_argument("--secure", action="store_true")
Andrew Scullbc7189d2018-08-14 09:35:13 +0100791 args = parser.parse_args()
David Brazdil2df24082019-09-05 11:55:08 +0100792
Andrew Scullbc7189d2018-08-14 09:35:13 +0100793 # Resolve some paths.
Andrew Scull7fd4bb72018-12-08 23:40:12 +0000794 image = os.path.join(args.out, args.image + ".bin")
795 initrd = None
David Brazdil2df24082019-09-05 11:55:08 +0100796 image_name = args.image
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100797
798 if not args.secure and args.initrd:
David Brazdil0dbb41f2019-09-09 18:03:35 +0100799 initrd_dir = os.path.join(args.out_initrd, "obj", args.initrd)
800 initrd = os.path.join(initrd_dir, "initrd.img")
David Brazdil2df24082019-09-05 11:55:08 +0100801 image_name += "_" + args.initrd
Andrew Walbranbc342d42019-02-05 16:56:02 +0000802 vm_args = args.vm_args or ""
David Brazdil2df24082019-09-05 11:55:08 +0100803
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100804 partitions = None
805 if args.driver == "fvp" and args.partitions_json is not None:
806 partitions_dir = os.path.join(args.out_partitions, "obj", args.partitions_json)
807 partitions = json.load(open(partitions_dir, "r"))
808
David Brazdil2df24082019-09-05 11:55:08 +0100809 # Create class which will manage all test artifacts.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100810 log_dir = os.path.join(args.log, "hafnium" if not args.secure else "spmc")
811 artifacts = ArtifactsManager(log_dir)
David Brazdil2df24082019-09-05 11:55:08 +0100812
813 # Create a driver for the platform we want to test on.
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100814 driver_args = DriverArgs(artifacts, image, initrd, vm_args, args.cpu,
815 partitions)
David Brazdil17e76652020-01-29 14:44:19 +0000816
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100817 if args.secure:
818 if args.driver != "fvp":
819 raise Exception("Secure tests can only run with fvp driver")
820 driver = FvpDriverSPMC(driver_args)
David Brazdil17e76652020-01-29 14:44:19 +0000821 else:
Olivier Depreza6d2e6d2020-11-06 18:09:50 +0100822 if args.driver == "qemu":
823 driver = QemuDriver(driver_args, args.out, args.tfa)
824 elif args.driver == "fvp":
825 driver = FvpDriverHypervisor(driver_args)
826 elif args.driver == "serial":
827 driver = SerialDriver(driver_args, args.serial_dev,
828 args.serial_baudrate, not args.serial_no_init_wait)
829 else:
830 raise Exception("Unknown driver name: {}".format(args.driver))
David Brazdil2df24082019-09-05 11:55:08 +0100831
832 # Create class which will drive test execution.
David Brazdil3cc24aa2019-09-27 10:24:41 +0100833 runner = TestRunner(artifacts, driver, image_name, args.suite, args.test,
Andrew Walbrane1fa70b2020-05-28 11:30:11 +0100834 args.skip_long_running_tests, args.force_long_running)
David Brazdil2df24082019-09-05 11:55:08 +0100835
836 # Run tests.
837 runner_result = runner.run_tests()
838
839 # Print error message if no tests were run as this is probably unexpected.
840 # Return suitable error code.
841 if runner_result.tests_run == 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100842 print("Error: no tests match")
843 return 10
David Brazdil2df24082019-09-05 11:55:08 +0100844 elif runner_result.tests_failed > 0:
Andrew Scullbc7189d2018-08-14 09:35:13 +0100845 return 1
846 else:
David Brazdil2df24082019-09-05 11:55:08 +0100847 return 0
Andrew Scullbc7189d2018-08-14 09:35:13 +0100848
849if __name__ == "__main__":
850 sys.exit(Main())