blob: e0c479350c6eab48a2f9f71707e8950acda31b8a [file] [log] [blame]
Archana1f1a34a2021-11-17 08:44:07 +05301#!/usr/bin/env python3
Archanae03960e2021-12-19 09:17:04 +05302"""Generate library/psa_crypto_driver_wrappers.c
3
Andrzej Kurek5c65c572022-04-13 14:28:52 -04004 This module is invoked by the build scripts to auto generate the
Archanae03960e2021-12-19 09:17:04 +05305 psa_crypto_driver_wrappers.c based on template files in
6 script/data_files/driver_templates/.
7"""
8# Copyright The Mbed TLS Contributors
9# SPDX-License-Identifier: Apache-2.0
10#
11# Licensed under the Apache License, Version 2.0 (the "License"); you may
12# not use this file except in compliance with the License.
13# You may obtain a copy of the License at
14#
15# http://www.apache.org/licenses/LICENSE-2.0
16#
17# Unless required by applicable law or agreed to in writing, software
18# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20# See the License for the specific language governing permissions and
21# limitations under the License.
Archana1f1a34a2021-11-17 08:44:07 +053022
23import sys
Archana1f1a34a2021-11-17 08:44:07 +053024import os
Archanae829cd62021-12-24 12:50:36 +053025import json
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +020026from typing import NewType, Dict, Any
27from traceback import format_tb
Archanae03960e2021-12-19 09:17:04 +053028import argparse
Archana31438052022-01-09 15:01:20 +053029import jsonschema
Archana1f1a34a2021-11-17 08:44:07 +053030import jinja2
Archanae03960e2021-12-19 09:17:04 +053031from mbedtls_dev import build_tree
Archana1f1a34a2021-11-17 08:44:07 +053032
Archanafdbbcba2022-02-27 05:38:55 +053033JSONSchema = NewType('JSONSchema', object)
Archanaa78dc702022-03-13 17:57:45 +053034# The Driver is an Object, but practically it's indexable and can called a dictionary to
35# keep MyPy happy till MyPy comes with a more composite type for JsonObjects.
36Driver = NewType('Driver', dict)
Archanafdbbcba2022-02-27 05:38:55 +053037
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +020038
39class JsonValidationException(Exception):
40 def __init__(self, message="Json Validation Failed"):
41 self.message = message
42 super().__init__(self.message)
43
44
Asfandyar Orakzaide088032022-09-17 22:07:58 +020045class DriverReaderException(Exception):
46 def __init__(self, message="Driver Reader Failed"):
47 self.message = message
48 super().__init__(self.message)
49
50
Archanae829cd62021-12-24 12:50:36 +053051def render(template_path: str, driver_jsoncontext: list) -> str:
Archanae03960e2021-12-19 09:17:04 +053052 """
Archanae829cd62021-12-24 12:50:36 +053053 Render template from the input file and driver JSON.
Archanae03960e2021-12-19 09:17:04 +053054 """
Archana6f21e452021-11-23 14:46:51 +053055 environment = jinja2.Environment(
56 loader=jinja2.FileSystemLoader(os.path.dirname(template_path)),
57 keep_trailing_newline=True)
58 template = environment.get_template(os.path.basename(template_path))
Archanae03960e2021-12-19 09:17:04 +053059
Archana31438052022-01-09 15:01:20 +053060 return template.render(drivers=driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053061
Archanae829cd62021-12-24 12:50:36 +053062
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +020063def generate_driver_wrapper_file(template_dir: str,
64 output_dir: str,
65 driver_jsoncontext: list) -> None:
Archanae03960e2021-12-19 09:17:04 +053066 """
67 Generate the file psa_crypto_driver_wrapper.c.
68 """
69 driver_wrapper_template_filename = \
Archanae829cd62021-12-24 12:50:36 +053070 os.path.join(template_dir, "psa_crypto_driver_wrappers.c.jinja")
Archana1f1a34a2021-11-17 08:44:07 +053071
Archanae829cd62021-12-24 12:50:36 +053072 result = render(driver_wrapper_template_filename, driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053073
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +020074 with open(file=os.path.join(output_dir, "psa_crypto_driver_wrappers.c"),
75 mode='w',
76 encoding='UTF-8') as out_file:
Archanae03960e2021-12-19 09:17:04 +053077 out_file.write(result)
Archana6f21e452021-11-23 14:46:51 +053078
Archanae829cd62021-12-24 12:50:36 +053079
Asfandyar Orakzaide088032022-09-17 22:07:58 +020080def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
Archanae829cd62021-12-24 12:50:36 +053081 """
Archanafdbbcba2022-02-27 05:38:55 +053082 Validate the Driver JSON against an appropriate schema
83 the schema passed could be that matching an opaque/ transparent driver.
Archana04cfe342022-01-09 13:28:28 +053084 """
Archanafdbbcba2022-02-27 05:38:55 +053085 driver_type = driverjson_data["type"]
86 driver_prefix = driverjson_data["prefix"]
Archana04cfe342022-01-09 13:28:28 +053087 try:
Archanafdbbcba2022-02-27 05:38:55 +053088 _schema = driverschema_list[driver_type]
89 jsonschema.validate(instance=driverjson_data, schema=_schema)
Archanafdbbcba2022-02-27 05:38:55 +053090 except KeyError as err:
Asfandyar Orakzaide088032022-09-17 22:07:58 +020091 # This could happen if the driverjson_data.type does not exist in the provided schema list
Archanafdbbcba2022-02-27 05:38:55 +053092 # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
93 # Print onto stdout and stderr.
94 print("Unknown Driver type " + driver_type +
95 " for driver " + driver_prefix, str(err))
96 print("Unknown Driver type " + driver_type +
97 " for driver " + driver_prefix, str(err), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +020098 raise JsonValidationException() from err
Archanafdbbcba2022-02-27 05:38:55 +053099
Archana04cfe342022-01-09 13:28:28 +0530100 except jsonschema.exceptions.ValidationError as err:
Archanafdbbcba2022-02-27 05:38:55 +0530101 # Print onto stdout and stderr.
102 print("Error: Failed to validate data file: {} using schema: {}."
103 "\n Exception Message: \"{}\""
104 " ".format(driverjson_data, _schema, str(err)))
105 print("Error: Failed to validate data file: {} using schema: {}."
106 "\n Exception Message: \"{}\""
107 " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200108 raise JsonValidationException() from err
Archana04cfe342022-01-09 13:28:28 +0530109
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200110
111def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +0200112 """loads validated json driver"""
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200113 with open(file=driver_file, mode='r', encoding='UTF-8') as f:
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200114 json_data = json.load(f)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200115 try:
116 validate_json(json_data, schemas)
117 except JsonValidationException as e:
118 raise DriverReaderException from e
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200119 return json_data
120
121
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200122def load_schemas(mbedtls_root: str) -> Dict[str, Any]:
Asfandyar Orakzaiac6f6502022-09-19 10:03:05 +0200123 """
124 Load schemas map
125 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200126 schema_file_paths = {
127 'transparent': os.path.join(mbedtls_root,
128 'scripts',
129 'data_files',
130 'driver_jsons',
131 'driver_transparent_schema.json'),
132 'opaque': os.path.join(mbedtls_root,
133 'scripts',
134 'data_files',
135 'driver_jsons',
Asfandyar Orakzai4ca4a932022-09-18 12:37:53 +0200136 'driver_opaque_schema.json')
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200137 }
138 driver_schema = {}
139 for key, file_path in schema_file_paths.items():
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200140 with open(file=file_path, mode='r', encoding='UTF-8') as file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200141 driver_schema[key] = json.load(file)
142 return driver_schema
143
144
145def read_driver_descriptions(mbedtls_root: str,
146 json_directory: str,
147 jsondriver_list: str) -> list:
Archana04cfe342022-01-09 13:28:28 +0530148 """
149 Merge driver JSON files into a single ordered JSON after validation.
Archanae829cd62021-12-24 12:50:36 +0530150 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200151 driver_schema = load_schemas(mbedtls_root)
Archana04cfe342022-01-09 13:28:28 +0530152
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200153 with open(file=os.path.join(json_directory, jsondriver_list),
154 mode='r',
155 encoding='UTF-8') as driver_list_file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200156 driver_list = json.load(driver_list_file)
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200157
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200158 return [load_driver(schemas=driver_schema,
159 driver_file=os.path.join(json_directory, driver_file_name))
160 for driver_file_name in driver_list]
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200161
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200162
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +0200163def trace_exception(e: Exception, file=sys.stderr) -> None:
164 """Prints exception trace to the given TextIO handle"""
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200165 print("Exception: type: %s, message: %s, trace: %s" % (
166 e.__class__, str(e), format_tb(e.__traceback__)
167 ), file)
Archanae829cd62021-12-24 12:50:36 +0530168
169
Archanae03960e2021-12-19 09:17:04 +0530170def main() -> int:
171 """
172 Main with command line arguments.
173 """
Archana4a9e0262021-12-19 13:34:30 +0530174 def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
Archana4a9e0262021-12-19 13:34:30 +0530175
Archanae03960e2021-12-19 09:17:04 +0530176 parser = argparse.ArgumentParser()
Archana22c78272022-04-11 10:12:08 +0530177 parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
Archanae03960e2021-12-19 09:17:04 +0530178 help='root directory of mbedtls source code')
Archana22c78272022-04-11 10:12:08 +0530179 parser.add_argument('--template-dir',
180 help='directory holding the driver templates')
181 parser.add_argument('--json-dir',
182 help='directory holding the driver JSONs')
Archana01aa39e2022-03-14 15:29:00 +0530183 parser.add_argument('output_directory', nargs='?',
184 help='output file\'s location')
Archanae03960e2021-12-19 09:17:04 +0530185 args = parser.parse_args()
Archana4a9e0262021-12-19 13:34:30 +0530186
Archana31438052022-01-09 15:01:20 +0530187 mbedtls_root = os.path.abspath(args.mbedtls_root)
Archana01aa39e2022-03-14 15:29:00 +0530188
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200189 output_directory = args.output_directory if args.output_directory is not None else \
190 os.path.join(mbedtls_root, 'library')
191 template_directory = args.template_dir if args.template_dir is not None else \
192 os.path.join(mbedtls_root,
193 'scripts',
194 'data_files',
195 'driver_templates')
196 json_directory = args.json_dir if args.json_dir is not None else \
197 os.path.join(mbedtls_root,
198 'scripts',
199 'data_files',
200 'driver_jsons')
Archanae03960e2021-12-19 09:17:04 +0530201
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200202 try:
203 # Read and validate list of driver jsons from driverlist.json
204 merged_driver_json = read_driver_descriptions(mbedtls_root,
205 json_directory,
206 'driverlist.json')
207 except DriverReaderException as e:
208 trace_exception(e)
Archanae829cd62021-12-24 12:50:36 +0530209 return 1
Archanafdbbcba2022-02-27 05:38:55 +0530210 generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
Archanae03960e2021-12-19 09:17:04 +0530211 return 0
212
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200213
Archanae03960e2021-12-19 09:17:04 +0530214if __name__ == '__main__':
215 sys.exit(main())