blob: b808ac9c637263dbbf819d8301d0cb1e8565d2a9 [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]:
123 """Load schemas map"""
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200124 schema_file_paths = {
125 'transparent': os.path.join(mbedtls_root,
126 'scripts',
127 'data_files',
128 'driver_jsons',
129 'driver_transparent_schema.json'),
130 'opaque': os.path.join(mbedtls_root,
131 'scripts',
132 'data_files',
133 'driver_jsons',
Asfandyar Orakzai4ca4a932022-09-18 12:37:53 +0200134 'driver_opaque_schema.json')
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200135 }
136 driver_schema = {}
137 for key, file_path in schema_file_paths.items():
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200138 with open(file=file_path, mode='r', encoding='UTF-8') as file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200139 driver_schema[key] = json.load(file)
140 return driver_schema
141
142
143def read_driver_descriptions(mbedtls_root: str,
144 json_directory: str,
145 jsondriver_list: str) -> list:
Archana04cfe342022-01-09 13:28:28 +0530146 """
147 Merge driver JSON files into a single ordered JSON after validation.
Archanae829cd62021-12-24 12:50:36 +0530148 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200149 driver_schema = load_schemas(mbedtls_root)
Archana04cfe342022-01-09 13:28:28 +0530150
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200151 with open(file=os.path.join(json_directory, jsondriver_list),
152 mode='r',
153 encoding='UTF-8') as driver_list_file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200154 driver_list = json.load(driver_list_file)
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200155
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200156 return [load_driver(schemas=driver_schema,
157 driver_file=os.path.join(json_directory, driver_file_name))
158 for driver_file_name in driver_list]
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200159
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200160
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +0200161def trace_exception(e: Exception, file=sys.stderr) -> None:
162 """Prints exception trace to the given TextIO handle"""
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200163 print("Exception: type: %s, message: %s, trace: %s" % (
164 e.__class__, str(e), format_tb(e.__traceback__)
165 ), file)
Archanae829cd62021-12-24 12:50:36 +0530166
167
Archanae03960e2021-12-19 09:17:04 +0530168def main() -> int:
169 """
170 Main with command line arguments.
Archanafdbbcba2022-02-27 05:38:55 +0530171 returns 1 when read_driver_descriptions returns False
Archanae03960e2021-12-19 09:17:04 +0530172 """
Archana4a9e0262021-12-19 13:34:30 +0530173 def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
Archana4a9e0262021-12-19 13:34:30 +0530174
Archanae03960e2021-12-19 09:17:04 +0530175 parser = argparse.ArgumentParser()
Archana22c78272022-04-11 10:12:08 +0530176 parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
Archanae03960e2021-12-19 09:17:04 +0530177 help='root directory of mbedtls source code')
Archana22c78272022-04-11 10:12:08 +0530178 parser.add_argument('--template-dir',
179 help='directory holding the driver templates')
180 parser.add_argument('--json-dir',
181 help='directory holding the driver JSONs')
Archana01aa39e2022-03-14 15:29:00 +0530182 parser.add_argument('output_directory', nargs='?',
183 help='output file\'s location')
Archanae03960e2021-12-19 09:17:04 +0530184 args = parser.parse_args()
Archana4a9e0262021-12-19 13:34:30 +0530185
Archana31438052022-01-09 15:01:20 +0530186 mbedtls_root = os.path.abspath(args.mbedtls_root)
Archana01aa39e2022-03-14 15:29:00 +0530187
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200188 output_directory = args.output_directory if args.output_directory is not None else \
189 os.path.join(mbedtls_root, 'library')
190 template_directory = args.template_dir if args.template_dir is not None else \
191 os.path.join(mbedtls_root,
192 'scripts',
193 'data_files',
194 'driver_templates')
195 json_directory = args.json_dir if args.json_dir is not None else \
196 os.path.join(mbedtls_root,
197 'scripts',
198 'data_files',
199 'driver_jsons')
Archanae03960e2021-12-19 09:17:04 +0530200
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200201 try:
202 # Read and validate list of driver jsons from driverlist.json
203 merged_driver_json = read_driver_descriptions(mbedtls_root,
204 json_directory,
205 'driverlist.json')
206 except DriverReaderException as e:
207 trace_exception(e)
Archanae829cd62021-12-24 12:50:36 +0530208 return 1
Archanafdbbcba2022-02-27 05:38:55 +0530209 generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
Archanae03960e2021-12-19 09:17:04 +0530210 return 0
211
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200212
Archanae03960e2021-12-19 09:17:04 +0530213if __name__ == '__main__':
214 sys.exit(main())