blob: ba5c4c27ab8f41707e335d7b4d48fd94a9894344 [file] [log] [blame]
Archana1f1a34a2021-11-17 08:44:07 +05301#!/usr/bin/env python3
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +00002"""Generate library/psa_crypto_driver_wrappers.h
3 library/psa_crypto_driver_wrappers_no_static.c
Archanae03960e2021-12-19 09:17:04 +05304
Andrzej Kurek5c65c572022-04-13 14:28:52 -04005 This module is invoked by the build scripts to auto generate the
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +00006 psa_crypto_driver_wrappers.h and psa_crypto_driver_wrappers_no_static
7 based on template files in script/data_files/driver_templates/.
Archanae03960e2021-12-19 09:17:04 +05308"""
9# Copyright The Mbed TLS Contributors
10# SPDX-License-Identifier: Apache-2.0
11#
12# Licensed under the Apache License, Version 2.0 (the "License"); you may
13# not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
Archana1f1a34a2021-11-17 08:44:07 +053023
24import sys
Archana1f1a34a2021-11-17 08:44:07 +053025import os
Archanae829cd62021-12-24 12:50:36 +053026import json
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +020027from typing import NewType, Dict, Any
28from traceback import format_tb
Archanae03960e2021-12-19 09:17:04 +053029import argparse
Archana31438052022-01-09 15:01:20 +053030import jsonschema
Archana1f1a34a2021-11-17 08:44:07 +053031import jinja2
Archanae03960e2021-12-19 09:17:04 +053032from mbedtls_dev import build_tree
Archana1f1a34a2021-11-17 08:44:07 +053033
Archanafdbbcba2022-02-27 05:38:55 +053034JSONSchema = NewType('JSONSchema', object)
Archanaa78dc702022-03-13 17:57:45 +053035# The Driver is an Object, but practically it's indexable and can called a dictionary to
36# keep MyPy happy till MyPy comes with a more composite type for JsonObjects.
37Driver = NewType('Driver', dict)
Archanafdbbcba2022-02-27 05:38:55 +053038
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +020039
40class JsonValidationException(Exception):
41 def __init__(self, message="Json Validation Failed"):
42 self.message = message
43 super().__init__(self.message)
44
45
Asfandyar Orakzaide088032022-09-17 22:07:58 +020046class DriverReaderException(Exception):
47 def __init__(self, message="Driver Reader Failed"):
48 self.message = message
49 super().__init__(self.message)
50
51
Archanae829cd62021-12-24 12:50:36 +053052def render(template_path: str, driver_jsoncontext: list) -> str:
Archanae03960e2021-12-19 09:17:04 +053053 """
Archanae829cd62021-12-24 12:50:36 +053054 Render template from the input file and driver JSON.
Archanae03960e2021-12-19 09:17:04 +053055 """
Archana6f21e452021-11-23 14:46:51 +053056 environment = jinja2.Environment(
57 loader=jinja2.FileSystemLoader(os.path.dirname(template_path)),
58 keep_trailing_newline=True)
59 template = environment.get_template(os.path.basename(template_path))
Archanae03960e2021-12-19 09:17:04 +053060
Archana31438052022-01-09 15:01:20 +053061 return template.render(drivers=driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053062
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +020063def generate_driver_wrapper_file(template_dir: str,
64 output_dir: str,
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +000065 template_file_name: str,
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +020066 driver_jsoncontext: list) -> None:
Archanae03960e2021-12-19 09:17:04 +053067 """
68 Generate the file psa_crypto_driver_wrapper.c.
69 """
70 driver_wrapper_template_filename = \
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +000071 os.path.join(template_dir, template_file_name)
Archana1f1a34a2021-11-17 08:44:07 +053072
Archanae829cd62021-12-24 12:50:36 +053073 result = render(driver_wrapper_template_filename, driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053074
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +000075 with open(file=os.path.join(output_dir, template_file_name.rsplit(".", 1)[0]),
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +020076 mode='w',
77 encoding='UTF-8') as out_file:
Archanae03960e2021-12-19 09:17:04 +053078 out_file.write(result)
Archana6f21e452021-11-23 14:46:51 +053079
Archanae829cd62021-12-24 12:50:36 +053080
Asfandyar Orakzaide088032022-09-17 22:07:58 +020081def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
Archanae829cd62021-12-24 12:50:36 +053082 """
Archanafdbbcba2022-02-27 05:38:55 +053083 Validate the Driver JSON against an appropriate schema
84 the schema passed could be that matching an opaque/ transparent driver.
Archana04cfe342022-01-09 13:28:28 +053085 """
Archanafdbbcba2022-02-27 05:38:55 +053086 driver_type = driverjson_data["type"]
87 driver_prefix = driverjson_data["prefix"]
Archana04cfe342022-01-09 13:28:28 +053088 try:
Archanafdbbcba2022-02-27 05:38:55 +053089 _schema = driverschema_list[driver_type]
90 jsonschema.validate(instance=driverjson_data, schema=_schema)
Archanafdbbcba2022-02-27 05:38:55 +053091 except KeyError as err:
Asfandyar Orakzaide088032022-09-17 22:07:58 +020092 # This could happen if the driverjson_data.type does not exist in the provided schema list
Archanafdbbcba2022-02-27 05:38:55 +053093 # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
94 # Print onto stdout and stderr.
95 print("Unknown Driver type " + driver_type +
96 " for driver " + driver_prefix, str(err))
97 print("Unknown Driver type " + driver_type +
98 " for driver " + driver_prefix, str(err), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +020099 raise JsonValidationException() from err
Archanafdbbcba2022-02-27 05:38:55 +0530100
Archana04cfe342022-01-09 13:28:28 +0530101 except jsonschema.exceptions.ValidationError as err:
Archanafdbbcba2022-02-27 05:38:55 +0530102 # Print onto stdout and stderr.
103 print("Error: Failed to validate data file: {} using schema: {}."
104 "\n Exception Message: \"{}\""
105 " ".format(driverjson_data, _schema, str(err)))
106 print("Error: Failed to validate data file: {} using schema: {}."
107 "\n Exception Message: \"{}\""
108 " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200109 raise JsonValidationException() from err
Archana04cfe342022-01-09 13:28:28 +0530110
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200111
112def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +0200113 """loads validated json driver"""
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200114 with open(file=driver_file, mode='r', encoding='UTF-8') as f:
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200115 json_data = json.load(f)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200116 try:
117 validate_json(json_data, schemas)
118 except JsonValidationException as e:
119 raise DriverReaderException from e
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200120 return json_data
121
122
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200123def load_schemas(mbedtls_root: str) -> Dict[str, Any]:
Asfandyar Orakzaiac6f6502022-09-19 10:03:05 +0200124 """
125 Load schemas map
126 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200127 schema_file_paths = {
128 'transparent': os.path.join(mbedtls_root,
129 'scripts',
130 'data_files',
131 'driver_jsons',
132 'driver_transparent_schema.json'),
133 'opaque': os.path.join(mbedtls_root,
134 'scripts',
135 'data_files',
136 'driver_jsons',
Asfandyar Orakzai4ca4a932022-09-18 12:37:53 +0200137 'driver_opaque_schema.json')
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200138 }
139 driver_schema = {}
140 for key, file_path in schema_file_paths.items():
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200141 with open(file=file_path, mode='r', encoding='UTF-8') as file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200142 driver_schema[key] = json.load(file)
143 return driver_schema
144
145
146def read_driver_descriptions(mbedtls_root: str,
147 json_directory: str,
148 jsondriver_list: str) -> list:
Archana04cfe342022-01-09 13:28:28 +0530149 """
150 Merge driver JSON files into a single ordered JSON after validation.
Archanae829cd62021-12-24 12:50:36 +0530151 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200152 driver_schema = load_schemas(mbedtls_root)
Archana04cfe342022-01-09 13:28:28 +0530153
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200154 with open(file=os.path.join(json_directory, jsondriver_list),
155 mode='r',
156 encoding='UTF-8') as driver_list_file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200157 driver_list = json.load(driver_list_file)
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200158
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200159 return [load_driver(schemas=driver_schema,
160 driver_file=os.path.join(json_directory, driver_file_name))
161 for driver_file_name in driver_list]
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200162
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200163
Asfandyar Orakzai9e6170d2022-09-17 23:37:16 +0200164def trace_exception(e: Exception, file=sys.stderr) -> None:
165 """Prints exception trace to the given TextIO handle"""
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200166 print("Exception: type: %s, message: %s, trace: %s" % (
167 e.__class__, str(e), format_tb(e.__traceback__)
168 ), file)
Archanae829cd62021-12-24 12:50:36 +0530169
170
Xiaokang Qianfe9666b2023-09-11 10:36:20 +0000171TEMPLATE_FILENAMES = ["psa_crypto_driver_wrappers.h.jinja",
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +0000172 "psa_crypto_driver_wrappers_no_static.c.jinja"]
173
Archanae03960e2021-12-19 09:17:04 +0530174def main() -> int:
175 """
176 Main with command line arguments.
177 """
Archana4a9e0262021-12-19 13:34:30 +0530178 def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
Archana4a9e0262021-12-19 13:34:30 +0530179
Archanae03960e2021-12-19 09:17:04 +0530180 parser = argparse.ArgumentParser()
Archana22c78272022-04-11 10:12:08 +0530181 parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
Archanae03960e2021-12-19 09:17:04 +0530182 help='root directory of mbedtls source code')
Archana22c78272022-04-11 10:12:08 +0530183 parser.add_argument('--template-dir',
184 help='directory holding the driver templates')
185 parser.add_argument('--json-dir',
186 help='directory holding the driver JSONs')
Archana01aa39e2022-03-14 15:29:00 +0530187 parser.add_argument('output_directory', nargs='?',
188 help='output file\'s location')
Archanae03960e2021-12-19 09:17:04 +0530189 args = parser.parse_args()
Archana4a9e0262021-12-19 13:34:30 +0530190
Archana31438052022-01-09 15:01:20 +0530191 mbedtls_root = os.path.abspath(args.mbedtls_root)
Archana01aa39e2022-03-14 15:29:00 +0530192
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200193 output_directory = args.output_directory if args.output_directory is not None else \
194 os.path.join(mbedtls_root, 'library')
195 template_directory = args.template_dir if args.template_dir is not None else \
196 os.path.join(mbedtls_root,
197 'scripts',
198 'data_files',
199 'driver_templates')
200 json_directory = args.json_dir if args.json_dir is not None else \
201 os.path.join(mbedtls_root,
202 'scripts',
203 'data_files',
204 'driver_jsons')
Archanae03960e2021-12-19 09:17:04 +0530205
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200206 try:
207 # Read and validate list of driver jsons from driverlist.json
208 merged_driver_json = read_driver_descriptions(mbedtls_root,
209 json_directory,
210 'driverlist.json')
211 except DriverReaderException as e:
212 trace_exception(e)
Archanae829cd62021-12-24 12:50:36 +0530213 return 1
Xiaokang Qian54a4fdf2023-09-11 02:39:27 +0000214 for template_filename in TEMPLATE_FILENAMES:
215 generate_driver_wrapper_file(template_directory, output_directory,
216 template_filename, merged_driver_json)
Archanae03960e2021-12-19 09:17:04 +0530217 return 0
218
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200219
Archanae03960e2021-12-19 09:17:04 +0530220if __name__ == '__main__':
221 sys.exit(main())