diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 09:13:47 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 09:13:47 +0000 |
commit | 102b0d2daa97dae68d3eed54d8fe37a9cc38a892 (patch) | |
tree | bcf648efac40ca6139842707f0eba5a4496a6dd2 /tools/sptool | |
parent | Initial commit. (diff) | |
download | arm-trusted-firmware-102b0d2daa97dae68d3eed54d8fe37a9cc38a892.tar.xz arm-trusted-firmware-102b0d2daa97dae68d3eed54d8fe37a9cc38a892.zip |
Adding upstream version 2.8.0+dfsg.upstream/2.8.0+dfsgupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'tools/sptool')
-rw-r--r-- | tools/sptool/Makefile | 50 | ||||
-rw-r--r-- | tools/sptool/sp_mk_generator.py | 232 | ||||
-rw-r--r-- | tools/sptool/spactions.py | 155 | ||||
-rwxr-xr-x | tools/sptool/sptool.py | 145 |
4 files changed, 582 insertions, 0 deletions
diff --git a/tools/sptool/Makefile b/tools/sptool/Makefile new file mode 100644 index 0000000..1fa85fb --- /dev/null +++ b/tools/sptool/Makefile @@ -0,0 +1,50 @@ +# +# Copyright (c) 2018-2020, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +# + +MAKE_HELPERS_DIRECTORY := ../../make_helpers/ +include ${MAKE_HELPERS_DIRECTORY}build_macros.mk +include ${MAKE_HELPERS_DIRECTORY}build_env.mk + +SPTOOL ?= sptool${BIN_EXT} +PROJECT := $(notdir ${SPTOOL}) +OBJECTS := sptool.o +V ?= 0 + +override CPPFLAGS += -D_GNU_SOURCE -D_XOPEN_SOURCE=700 +HOSTCCFLAGS := -Wall -Werror -pedantic -std=c99 +ifeq (${DEBUG},1) + HOSTCCFLAGS += -g -O0 -DDEBUG +else + HOSTCCFLAGS += -O2 +endif + +ifeq (${V},0) + Q := @ +else + Q := +endif + +INCLUDE_PATHS := -I../../include/tools_share + +HOSTCC ?= gcc + +.PHONY: all clean distclean + +all: ${PROJECT} + +${PROJECT}: ${OBJECTS} Makefile + @echo " HOSTLD $@" + ${Q}${HOSTCC} ${OBJECTS} -o $@ ${LDLIBS} + @${ECHO_BLANK_LINE} + @echo "Built $@ successfully" + @${ECHO_BLANK_LINE} + +%.o: %.c Makefile + @echo " HOSTCC $<" + ${Q}${HOSTCC} -c ${CPPFLAGS} ${HOSTCCFLAGS} ${INCLUDE_PATHS} $< -o $@ + +clean: + $(call SHELL_DELETE_ALL, ${PROJECT} ${OBJECTS}) diff --git a/tools/sptool/sp_mk_generator.py b/tools/sptool/sp_mk_generator.py new file mode 100644 index 0000000..f3af584 --- /dev/null +++ b/tools/sptool/sp_mk_generator.py @@ -0,0 +1,232 @@ +#!/usr/bin/python3 +# Copyright (c) 2020-2022, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +""" +This script is invoked by Make system and generates secure partition makefile. +It expects platform provided secure partition layout file which contains list +of Secure Partition Images and Partition manifests(PM). +Layout file can exist outside of TF-A tree and the paths of Image and PM files +must be relative to it. + +This script parses the layout file and generates a make file which updates +FDT_SOURCES, FIP_ARGS, CRT_ARGS and SPTOOL_ARGS which are used in later build +steps. +If the SP entry in the layout file has a "uuid" field the scripts gets the UUID +from there, otherwise it parses the associated partition manifest and extracts +the UUID from there. + +param1: Generated mk file "sp_gen.mk" +param2: "SP_LAYOUT_FILE", json file containing platform provided information +param3: plat out directory +param4: CoT parameter + +Generated "sp_gen.mk" file contains triplet of following information for each +Secure Partition entry + FDT_SOURCES += sp1.dts + SPTOOL_ARGS += -i sp1.bin:sp1.dtb -o sp1.pkg + FIP_ARGS += --blob uuid=XXXXX-XXX...,file=sp1.pkg + CRT_ARGS += --sp-pkg1 sp1.pkg + +A typical SP_LAYOUT_FILE file will look like +{ + "SP1" : { + "image": "sp1.bin", + "pm": "test/sp1.dts" + }, + + "SP2" : { + "image": "sp2.bin", + "pm": "test/sp2.dts", + "uuid": "1b1820fe-48f7-4175-8999-d51da00b7c9f" + } + + ... +} + +""" +import json +import os +import re +import sys +import uuid +from spactions import SpSetupActions + +MAX_SP = 8 +UUID_LEN = 4 + +# Some helper functions to access args propagated to the action functions in +# SpSetupActions framework. +def check_sp_mk_gen(args :dict): + if "sp_gen_mk" not in args.keys(): + raise Exception(f"Path to file sp_gen.mk needs to be in 'args'.") + +def check_out_dir(args :dict): + if "out_dir" not in args.keys() or not os.path.isdir(args["out_dir"]): + raise Exception("Define output folder with \'out_dir\' key.") + +def check_sp_layout_dir(args :dict): + if "sp_layout_dir" not in args.keys() or not os.path.isdir(args["sp_layout_dir"]): + raise Exception("Define output folder with \'sp_layout_dir\' key.") + +def write_to_sp_mk_gen(content, args :dict): + check_sp_mk_gen(args) + with open(args["sp_gen_mk"], "a") as f: + f.write(f"{content}\n") + +def get_sp_manifest_full_path(sp_node, args :dict): + check_sp_layout_dir(args) + return os.path.join(args["sp_layout_dir"], get_file_from_layout(sp_node["pm"])) + +def get_sp_img_full_path(sp_node, args :dict): + check_sp_layout_dir(args) + return os.path.join(args["sp_layout_dir"], get_file_from_layout(sp_node["image"])) + +def get_sp_pkg(sp, args :dict): + check_out_dir(args) + return os.path.join(args["out_dir"], f"{sp}.pkg") + +def is_line_in_sp_gen(line, args :dict): + with open(args["sp_gen_mk"], "r") as f: + sppkg_rule = [l for l in f if line in l] + return len(sppkg_rule) != 0 + +def get_file_from_layout(node): + ''' Helper to fetch a file path from sp_layout.json. ''' + if type(node) is dict and "file" in node.keys(): + return node["file"] + return node + +def get_offset_from_layout(node): + ''' Helper to fetch an offset from sp_layout.json. ''' + if type(node) is dict and "offset" in node.keys(): + return int(node["offset"], 0) + return None + +def get_image_offset(node): + ''' Helper to fetch image offset from sp_layout.json ''' + return get_offset_from_layout(node["image"]) + +def get_pm_offset(node): + ''' Helper to fetch pm offset from sp_layout.json ''' + return get_offset_from_layout(node["pm"]) + +@SpSetupActions.sp_action(global_action=True) +def check_max_sps(sp_layout, _, args :dict): + ''' Check validate the maximum number of SPs is respected. ''' + if len(sp_layout.keys()) > MAX_SP: + raise Exception(f"Too many SPs in SP layout file. Max: {MAX_SP}") + return args + +@SpSetupActions.sp_action +def gen_fdt_sources(sp_layout, sp, args :dict): + ''' Generate FDT_SOURCES values for a given SP. ''' + manifest_path = get_sp_manifest_full_path(sp_layout[sp], args) + write_to_sp_mk_gen(f"FDT_SOURCES += {manifest_path}", args) + return args + +@SpSetupActions.sp_action +def gen_sptool_args(sp_layout, sp, args :dict): + ''' Generate Sp Pkgs rules. ''' + sp_pkg = get_sp_pkg(sp, args) + sp_dtb_name = os.path.basename(get_file_from_layout(sp_layout[sp]["pm"]))[:-1] + "b" + sp_dtb = os.path.join(args["out_dir"], f"fdts/{sp_dtb_name}") + + # Do not generate rule if already there. + if is_line_in_sp_gen(f'{sp_pkg}:', args): + return args + write_to_sp_mk_gen(f"SP_PKGS += {sp_pkg}\n", args) + + sptool_args = f" -i {get_sp_img_full_path(sp_layout[sp], args)}:{sp_dtb}" + pm_offset = get_pm_offset(sp_layout[sp]) + sptool_args += f" --pm-offset {pm_offset}" if pm_offset is not None else "" + image_offset = get_image_offset(sp_layout[sp]) + sptool_args += f" --img-offset {image_offset}" if image_offset is not None else "" + sptool_args += f" -o {sp_pkg}" + sppkg_rule = f''' +{sp_pkg}: {sp_dtb} +\t$(Q)echo Generating {sp_pkg} +\t$(Q)$(PYTHON) $(SPTOOL) {sptool_args} +''' + write_to_sp_mk_gen(sppkg_rule, args) + return args + +@SpSetupActions.sp_action(global_action=True, exec_order=1) +def check_dualroot(sp_layout, _, args :dict): + ''' Validate the amount of SPs from SiP and Platform owners. ''' + if not args.get("dualroot"): + return args + args["split"] = int(MAX_SP / 2) + owners = [sp_layout[sp].get("owner") for sp in sp_layout] + args["plat_max_count"] = owners.count("Plat") + # If it is owned by the platform owner, it is assigned to the SiP. + args["sip_max_count"] = len(sp_layout.keys()) - args["plat_max_count"] + if args["sip_max_count"] > args["split"] or args["sip_max_count"] > args["split"]: + print(f"WARN: SiP Secure Partitions should not be more than {args['split']}") + # Counters for gen_crt_args. + args["sip_count"] = 1 + args["plat_count"] = 1 + return args + +@SpSetupActions.sp_action +def gen_crt_args(sp_layout, sp, args :dict): + ''' Append CRT_ARGS. ''' + # If "dualroot" is configured, 'sp_pkg_idx' depends on whether the SP is owned + # by the "SiP" or the "Plat". + if args.get("dualroot"): + # If the owner is not specified as "Plat", default to "SiP". + if sp_layout[sp].get("owner") == "Plat": + if args["plat_count"] > args["plat_max_count"]: + raise ValueError("plat_count can't surpass plat_max_count in args.") + sp_pkg_idx = args["plat_count"] + args["split"] + args["plat_count"] += 1 + else: + if args["sip_count"] > args["sip_max_count"]: + raise ValueError("sip_count can't surpass sip_max_count in args.") + sp_pkg_idx = args["sip_count"] + args["sip_count"] += 1 + else: + sp_pkg_idx = [k for k in sp_layout.keys()].index(sp) + 1 + write_to_sp_mk_gen(f"CRT_ARGS += --sp-pkg{sp_pkg_idx} {get_sp_pkg(sp, args)}\n", args) + return args + +@SpSetupActions.sp_action +def gen_fiptool_args(sp_layout, sp, args :dict): + ''' Generate arguments for the FIP Tool. ''' + if "uuid" in sp_layout[sp]: + # Extract the UUID from the JSON file if the SP entry has a 'uuid' field + uuid_std = uuid.UUID(sp_layout[sp]['uuid']) + else: + with open(get_sp_manifest_full_path(sp_layout[sp], args), "r") as pm_f: + uuid_lines = [l for l in pm_f if 'uuid' in l] + assert(len(uuid_lines) == 1) + # The uuid field in SP manifest is the little endian representation + # mapped to arguments as described in SMCCC section 5.3. + # Convert each unsigned integer value to a big endian representation + # required by fiptool. + uuid_parsed = re.findall("0x([0-9a-f]+)", uuid_lines[0]) + y = list(map(bytearray.fromhex, uuid_parsed)) + z = [int.from_bytes(i, byteorder='little', signed=False) for i in y] + uuid_std = uuid.UUID(f'{z[0]:08x}{z[1]:08x}{z[2]:08x}{z[3]:08x}') + write_to_sp_mk_gen(f"FIP_ARGS += --blob uuid={str(uuid_std)},file={get_sp_pkg(sp, args)}\n", args) + return args + +def init_sp_actions(sys): + sp_layout_file = os.path.abspath(sys.argv[2]) + with open(sp_layout_file) as json_file: + sp_layout = json.load(json_file) + # Initialize arguments for the SP actions framework + args = {} + args["sp_gen_mk"] = os.path.abspath(sys.argv[1]) + args["sp_layout_dir"] = os.path.dirname(sp_layout_file) + args["out_dir"] = os.path.abspath(sys.argv[3]) + args["dualroot"] = sys.argv[4] == "dualroot" + #Clear content of file "sp_gen.mk". + with open(args["sp_gen_mk"], "w"): + None + return args, sp_layout + +if __name__ == "__main__": + args, sp_layout = init_sp_actions(sys) + SpSetupActions.run_actions(sp_layout, args) diff --git a/tools/sptool/spactions.py b/tools/sptool/spactions.py new file mode 100644 index 0000000..ff28ebb --- /dev/null +++ b/tools/sptool/spactions.py @@ -0,0 +1,155 @@ +#!/usr/bin/python3 +# Copyright (c) 2022, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause +''' +This is a python module for defining and executing SP setup actions, targeting +a system deploying an SPM implementation. +Each action consists of a function, that processes the SP layout json file and +other provided arguments. +At the core of this is the SpSetupActions which provides a means to register +the functions into a table of actions, and execute them all when invoking +SpSetupActions.run_actions. +Registering the function is done by using the decorator '@SpSetupActions.sp_action' +at function definition. + +Functions can be called: +- once only, or per SP defined in the SP layout file; +- following an order, from lowest to highest of their execution order. +More information in the doc comments below. +''' +import bisect + +DEFAULT_ACTION_ORDER = 100 + +class _ConfiguredAction: + """ + Wraps action function with its configuration. + """ + def __init__(self, action, exec_order=DEFAULT_ACTION_ORDER, global_action=True, log_calls = False): + self.exec_order = exec_order + self.__name__ = action.__name__ + def logged_action(action): + def inner_logged_action(sp_layout, sp, args :dict): + print(f"Calling {action.__name__} -> {sp}") + return action(sp_layout, sp, args) + return inner_logged_action + self.action = logged_action(action) if log_calls is True else action + self.global_action = global_action + + def __lt__(self, other): + """ + To allow for ordered inserts in a list of actions. + """ + return self.exec_order < other.exec_order + + def __call__(self, sp_layout, sp, args :dict): + """ + Calls action function. + """ + return self.action(sp_layout, sp, args) + + def __repr__(self) -> str: + """ + Pretty format to show debug information about the action. + """ + return f"func: {self.__name__}; global:{self.global_action}; exec_order: {self.exec_order}" + +class SpSetupActions: + actions = [] + + def sp_action(in_action = None, global_action = False, log_calls=False, exec_order=DEFAULT_ACTION_ORDER): + """ + Function decorator that registers and configures action. + + :param in_action - function to register + :param global_action - make the function global, i.e. make it be + only called once. + :param log_calls - at every call to action, a useful log will be printed. + :param exec_order - action's calling order. + """ + def append_action(action): + action = _ConfiguredAction(action, exec_order, global_action, log_calls) + bisect.insort(SpSetupActions.actions, action) + return action + if in_action is not None: + return append_action(in_action) + return append_action + + def run_actions(sp_layout: dict, args: dict, verbose=False): + """ + Executes all actions in accordance to their registering configuration: + - If set as "global" it will be called once. + - Actions are called respecting the order established by their "exec_order" field. + + :param sp_layout - dictionary containing the SP layout information. + :param args - arguments to be propagated through the call of actions. + :param verbose - prints actions information in order of execution. + """ + args["called"] = [] # for debug purposes + def append_called(action, sp, args :dict): + args["called"].append(f"{action.__name__} -> {sp}") + return args + + for action in SpSetupActions.actions: + if verbose: + print(f"Calling {action}") + if action.global_action: + scope = "global" + args = action(sp_layout, scope, args) + args = append_called(action, scope, args) + else: + # Functions that are not global called for each SP defined in + # the SP layout. + for sp in sp_layout.keys(): + args = action(sp_layout, sp, args) + args = append_called(action, sp, args) + +if __name__ == "__main__": + # Executing this module will have the following test code/playground executed + sp_layout = { + "partition1" : { + "boot-info": True, + "image": { + "file": "partition.bin", + "offset":"0x2000" + }, + "pm": { + "file": "cactus.dts", + "offset":"0x1000" + }, + "owner": "SiP" + }, + "partition2" : { + "image": "partition.bin", + "pm": "cactus-secondary.dts", + "owner": "Plat" + }, + "partition3" : { + "image": "partition.bin", + "pm": "cactus-tertiary.dts", + "owner": "Plat" + }, + "partition4" : { + "image": "ivy.bin", + "pm": "ivy.dts", + "owner": "Plat" + } + } + + #Example of how to use this module + @SpSetupActions.sp_action(global_action=True) + def my_action1(sp_layout, _, args :dict): + print(f"inside function my_action1{sp_layout}\n\n args:{args})") + return args # Always return args in action function. + @SpSetupActions.sp_action(exec_order=1) + def my_action2(sp_layout, sp_name, args :dict): + print(f"inside function my_action2; SP: {sp_name} {sp_layout} args:{args}") + return args + + # Example arguments to be propagated through the functions. + # 'args' can be extended in the action functions. + args = dict() + args["arg1"] = 0xEEE + args["arg2"] = 0xFF + SpSetupActions.run_actions(sp_layout, args) diff --git a/tools/sptool/sptool.py b/tools/sptool/sptool.py new file mode 100755 index 0000000..ae7df92 --- /dev/null +++ b/tools/sptool/sptool.py @@ -0,0 +1,145 @@ +#!/usr/bin/python3 +# Copyright (c) 2022, Arm Limited. All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# +# Copyright 2022 The Hafnium Authors. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://opensource.org/licenses/BSD-3-Clause. + +""" +Script which generates a Secure Partition package. +https://trustedfirmware-a.readthedocs.io/en/latest/components/secure-partition-manager.html#secure-partition-packages +""" + +import argparse +from collections import namedtuple +import sys +from shutil import copyfileobj +import os + +HF_PAGE_SIZE = 0x1000 # bytes +HEADER_ELEMENT_BYTES = 4 # bytes +MANIFEST_IMAGE_SPLITTER=':' +PM_OFFSET_DEFAULT = "0x1000" +IMG_OFFSET_DEFAULT = "0x4000" + +def split_dtb_bin(i : str): + return i.split(MANIFEST_IMAGE_SPLITTER) + +def align_to_page(n): + return HF_PAGE_SIZE * \ + (round(n / HF_PAGE_SIZE) + \ + (1 if n % HF_PAGE_SIZE else 0)) + +def to_bytes(value): + return int(value).to_bytes(HEADER_ELEMENT_BYTES, 'little') + +class SpPkg: + def __init__(self, pm_path : str, img_path : str, pm_offset: int, + img_offset: int): + if not os.path.isfile(pm_path) or not os.path.isfile(img_path): + raise Exception(f"Parameters should be path. \ + manifest: {pm_path}; img: {img_path}") + self.pm_path = pm_path + self.img_path = img_path + self._SpPkgHeader = namedtuple("SpPkgHeader", + ("magic", "version", + "pm_offset", "pm_size", + "img_offset", "img_size")) + + if pm_offset >= img_offset: + raise ValueError("pm_offset must be smaller than img_offset") + + is_hfpage_aligned = lambda val : val % HF_PAGE_SIZE == 0 + if not is_hfpage_aligned(pm_offset) or not is_hfpage_aligned(img_offset): + raise ValueError(f"Offsets provided need to be page aligned: pm-{pm_offset}, img-{img_offset}") + + if img_offset - pm_offset < self.pm_size: + raise ValueError(f"pm_offset and img_offset do not fit the specified file:{pm_path})") + + self.pm_offset = pm_offset + self.img_offset = img_offset + + def __str__(self): + return \ + f'''--SP package Info-- + header:{self.header} + pm: {self.pm_path} + img: {self.img_path} + ''' + + @property + def magic(self): + return "SPKG".encode() + + @property + def version(self): + return 0x2 + + @property + def pm_size(self): + return os.path.getsize(self.pm_path) + + @property + def img_size(self): + return os.path.getsize(self.img_path) + + @property + def header(self): + return self._SpPkgHeader( + self.magic, + self.version, + self.pm_offset, + self.pm_size, + self.img_offset, + self.img_size) + + @property + def header_size(self): + return len(self._SpPkgHeader._fields) + + def generate(self, f_out : str): + with open(f_out, "wb+") as output: + for h in self.header: + to_write = h if type(h) is bytes else to_bytes(h) + output.write(to_write) + output.seek(self.pm_offset) + with open(self.pm_path, "rb") as pm: + copyfileobj(pm, output) + output.seek(self.img_offset) + with open(self.img_path, "rb") as img: + copyfileobj(img, output) + +def Main(): + parser = argparse.ArgumentParser() + parser.add_argument("-i", required=True, + help="path to partition's image and manifest separated by a colon.") + parser.add_argument("--pm-offset", required=False, default=PM_OFFSET_DEFAULT, + help="set partitition manifest offset.") + parser.add_argument("--img-offset", required=False, default=IMG_OFFSET_DEFAULT, + help="set partition image offset.") + parser.add_argument("-o", required=True, help="set output file path.") + parser.add_argument("-v", required=False, action="store_true", + help="print package information.") + args = parser.parse_args() + + if not os.path.exists(os.path.dirname(args.o)): + raise Exception("Provide a valid output file path!\n") + + image_path, manifest_path = split_dtb_bin(args.i) + pm_offset = int(args.pm_offset, 0) + img_offset = int(args.img_offset, 0) + pkg = SpPkg(manifest_path, image_path, pm_offset, img_offset) + pkg.generate(args.o) + + if args.v is True: + print(pkg) + + return 0 + +if __name__ == "__main__": + sys.exit(Main()) |