1#!/usr/bin/env python3 2"""Generate library/psa_crypto_driver_wrappers.h 3 library/psa_crypto_driver_wrappers_no_static.c 4 5 This module is invoked by the build scripts to auto generate the 6 psa_crypto_driver_wrappers.h and psa_crypto_driver_wrappers_no_static 7 based on template files in script/data_files/driver_templates/. 8""" 9# Copyright The Mbed TLS Contributors 10# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 11 12import sys 13import os 14import json 15from typing import NewType, Dict, Any 16from traceback import format_tb 17import argparse 18import jsonschema 19import jinja2 20 21import framework_scripts_path # pylint: disable=unused-import 22from mbedtls_framework import build_tree 23 24JSONSchema = NewType('JSONSchema', object) 25# The Driver is an Object, but practically it's indexable and can called a dictionary to 26# keep MyPy happy till MyPy comes with a more composite type for JsonObjects. 27Driver = NewType('Driver', dict) 28 29 30class JsonValidationException(Exception): 31 def __init__(self, message="Json Validation Failed"): 32 self.message = message 33 super().__init__(self.message) 34 35 36class DriverReaderException(Exception): 37 def __init__(self, message="Driver Reader Failed"): 38 self.message = message 39 super().__init__(self.message) 40 41 42def render(template_path: str, driver_jsoncontext: list) -> str: 43 """ 44 Render template from the input file and driver JSON. 45 """ 46 environment = jinja2.Environment( 47 loader=jinja2.FileSystemLoader(os.path.dirname(template_path)), 48 keep_trailing_newline=True) 49 template = environment.get_template(os.path.basename(template_path)) 50 51 return template.render(drivers=driver_jsoncontext) 52 53def generate_driver_wrapper_file(template_dir: str, 54 output_dir: str, 55 template_file_name: str, 56 driver_jsoncontext: list) -> None: 57 """ 58 Generate the file psa_crypto_driver_wrapper.c. 59 """ 60 driver_wrapper_template_filename = \ 61 os.path.join(template_dir, template_file_name) 62 63 result = render(driver_wrapper_template_filename, driver_jsoncontext) 64 65 with open(file=os.path.join(output_dir, os.path.splitext(template_file_name)[0]), 66 mode='w', 67 encoding='UTF-8') as out_file: 68 out_file.write(result) 69 70 71def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None: 72 """ 73 Validate the Driver JSON against an appropriate schema 74 the schema passed could be that matching an opaque/ transparent driver. 75 """ 76 driver_type = driverjson_data["type"] 77 driver_prefix = driverjson_data["prefix"] 78 try: 79 _schema = driverschema_list[driver_type] 80 jsonschema.validate(instance=driverjson_data, schema=_schema) 81 except KeyError as err: 82 # This could happen if the driverjson_data.type does not exist in the provided schema list 83 # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema} 84 # Print onto stdout and stderr. 85 print("Unknown Driver type " + driver_type + 86 " for driver " + driver_prefix, str(err)) 87 print("Unknown Driver type " + driver_type + 88 " for driver " + driver_prefix, str(err), file=sys.stderr) 89 raise JsonValidationException() from err 90 91 except jsonschema.exceptions.ValidationError as err: 92 # Print onto stdout and stderr. 93 print("Error: Failed to validate data file: {} using schema: {}." 94 "\n Exception Message: \"{}\"" 95 " ".format(driverjson_data, _schema, str(err))) 96 print("Error: Failed to validate data file: {} using schema: {}." 97 "\n Exception Message: \"{}\"" 98 " ".format(driverjson_data, _schema, str(err)), file=sys.stderr) 99 raise JsonValidationException() from err 100 101 102def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any: 103 """loads validated json driver""" 104 with open(file=driver_file, mode='r', encoding='UTF-8') as f: 105 json_data = json.load(f) 106 try: 107 validate_json(json_data, schemas) 108 except JsonValidationException as e: 109 raise DriverReaderException from e 110 return json_data 111 112 113def load_schemas(project_root: str) -> Dict[str, Any]: 114 """ 115 Load schemas map 116 """ 117 schema_file_paths = { 118 'transparent': os.path.join(project_root, 119 'scripts', 120 'data_files', 121 'driver_jsons', 122 'driver_transparent_schema.json'), 123 'opaque': os.path.join(project_root, 124 'scripts', 125 'data_files', 126 'driver_jsons', 127 'driver_opaque_schema.json') 128 } 129 driver_schema = {} 130 for key, file_path in schema_file_paths.items(): 131 with open(file=file_path, mode='r', encoding='UTF-8') as file: 132 driver_schema[key] = json.load(file) 133 return driver_schema 134 135 136def read_driver_descriptions(project_root: str, 137 json_directory: str, 138 jsondriver_list: str) -> list: 139 """ 140 Merge driver JSON files into a single ordered JSON after validation. 141 """ 142 driver_schema = load_schemas(project_root) 143 144 with open(file=os.path.join(json_directory, jsondriver_list), 145 mode='r', 146 encoding='UTF-8') as driver_list_file: 147 driver_list = json.load(driver_list_file) 148 149 return [load_driver(schemas=driver_schema, 150 driver_file=os.path.join(json_directory, driver_file_name)) 151 for driver_file_name in driver_list] 152 153 154def trace_exception(e: Exception, file=sys.stderr) -> None: 155 """Prints exception trace to the given TextIO handle""" 156 print("Exception: type: %s, message: %s, trace: %s" % ( 157 e.__class__, str(e), format_tb(e.__traceback__) 158 ), file) 159 160 161TEMPLATE_FILENAMES = ["psa_crypto_driver_wrappers.h.jinja", 162 "psa_crypto_driver_wrappers_no_static.c.jinja"] 163 164def main() -> int: 165 """ 166 Main with command line arguments. 167 """ 168 def_arg_project_root = build_tree.guess_project_root() 169 170 parser = argparse.ArgumentParser() 171 parser.add_argument('--project-root', default=def_arg_project_root, 172 help='root directory of repo source code') 173 parser.add_argument('--template-dir', 174 help='directory holding the driver templates') 175 parser.add_argument('--json-dir', 176 help='directory holding the driver JSONs') 177 parser.add_argument('output_directory', nargs='?', 178 help='output file\'s location') 179 args = parser.parse_args() 180 181 project_root = os.path.abspath(args.project_root) 182 183 crypto_core_directory = build_tree.crypto_core_directory(project_root) 184 185 output_directory = args.output_directory if args.output_directory is not None else \ 186 crypto_core_directory 187 188 template_directory = args.template_dir if args.template_dir is not None else \ 189 os.path.join(project_root, 190 'scripts', 191 'data_files', 192 'driver_templates') 193 json_directory = args.json_dir if args.json_dir is not None else \ 194 os.path.join(project_root, 195 'scripts', 196 'data_files', 197 'driver_jsons') 198 199 try: 200 # Read and validate list of driver jsons from driverlist.json 201 merged_driver_json = read_driver_descriptions(project_root, 202 json_directory, 203 'driverlist.json') 204 except DriverReaderException as e: 205 trace_exception(e) 206 return 1 207 for template_filename in TEMPLATE_FILENAMES: 208 generate_driver_wrapper_file(template_directory, output_directory, 209 template_filename, merged_driver_json) 210 return 0 211 212 213if __name__ == '__main__': 214 sys.exit(main()) 215