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