blob: 72a8c6182fb4828235820572f900b74e826f6622 [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
Archana31438052022-01-09 15:01:20 +053063def generate_driver_wrapper_file(template_dir: str, \
64 output_dir: str, driver_jsoncontext: list) -> None:
Archanae03960e2021-12-19 09:17:04 +053065 """
66 Generate the file psa_crypto_driver_wrapper.c.
67 """
68 driver_wrapper_template_filename = \
Archanae829cd62021-12-24 12:50:36 +053069 os.path.join(template_dir, "psa_crypto_driver_wrappers.c.jinja")
Archana1f1a34a2021-11-17 08:44:07 +053070
Archanae829cd62021-12-24 12:50:36 +053071 result = render(driver_wrapper_template_filename, driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053072
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +020073 with open(file=os.path.join(output_dir, "psa_crypto_driver_wrappers.c"),
74 mode='w',
75 encoding='UTF-8') as out_file:
Archanae03960e2021-12-19 09:17:04 +053076 out_file.write(result)
Archana6f21e452021-11-23 14:46:51 +053077
Archanae829cd62021-12-24 12:50:36 +053078
Asfandyar Orakzaide088032022-09-17 22:07:58 +020079def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
Archanae829cd62021-12-24 12:50:36 +053080 """
Archanafdbbcba2022-02-27 05:38:55 +053081 Validate the Driver JSON against an appropriate schema
82 the schema passed could be that matching an opaque/ transparent driver.
Archana04cfe342022-01-09 13:28:28 +053083 """
Archanafdbbcba2022-02-27 05:38:55 +053084 driver_type = driverjson_data["type"]
85 driver_prefix = driverjson_data["prefix"]
Archana04cfe342022-01-09 13:28:28 +053086 try:
Archanafdbbcba2022-02-27 05:38:55 +053087 _schema = driverschema_list[driver_type]
88 jsonschema.validate(instance=driverjson_data, schema=_schema)
Archanafdbbcba2022-02-27 05:38:55 +053089 except KeyError as err:
Asfandyar Orakzaide088032022-09-17 22:07:58 +020090 # This could happen if the driverjson_data.type does not exist in the provided schema list
Archanafdbbcba2022-02-27 05:38:55 +053091 # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
92 # Print onto stdout and stderr.
93 print("Unknown Driver type " + driver_type +
94 " for driver " + driver_prefix, str(err))
95 print("Unknown Driver type " + driver_type +
96 " for driver " + driver_prefix, str(err), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +020097 raise JsonValidationException() from err
Archanafdbbcba2022-02-27 05:38:55 +053098
Archana04cfe342022-01-09 13:28:28 +053099 except jsonschema.exceptions.ValidationError as err:
Archanafdbbcba2022-02-27 05:38:55 +0530100 # Print onto stdout and stderr.
101 print("Error: Failed to validate data file: {} using schema: {}."
102 "\n Exception Message: \"{}\""
103 " ".format(driverjson_data, _schema, str(err)))
104 print("Error: Failed to validate data file: {} using schema: {}."
105 "\n Exception Message: \"{}\""
106 " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200107 raise JsonValidationException() from err
Archana04cfe342022-01-09 13:28:28 +0530108
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200109
110def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200111 with open(file=driver_file, mode='r', encoding='UTF-8') as f:
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200112 json_data = json.load(f)
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200113 try:
114 validate_json(json_data, schemas)
115 except JsonValidationException as e:
116 raise DriverReaderException from e
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200117 return json_data
118
119
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200120def load_schemas(mbedtls_root: str) -> Dict[str, Any]:
121 """Load schemas map"""
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200122 schema_file_paths = {
123 'transparent': os.path.join(mbedtls_root,
124 'scripts',
125 'data_files',
126 'driver_jsons',
127 'driver_transparent_schema.json'),
128 'opaque': os.path.join(mbedtls_root,
129 'scripts',
130 'data_files',
131 'driver_jsons',
132 'driver_transparent_schema.json')
133 }
134 driver_schema = {}
135 for key, file_path in schema_file_paths.items():
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200136 with open(file=file_path, mode='r', encoding='UTF-8') as file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200137 driver_schema[key] = json.load(file)
138 return driver_schema
139
140
141def read_driver_descriptions(mbedtls_root: str,
142 json_directory: str,
143 jsondriver_list: str) -> list:
Archana04cfe342022-01-09 13:28:28 +0530144 """
145 Merge driver JSON files into a single ordered JSON after validation.
Archanae829cd62021-12-24 12:50:36 +0530146 """
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200147 driver_schema = load_schemas(mbedtls_root)
Archana04cfe342022-01-09 13:28:28 +0530148
Asfandyar Orakzai5c9569a2022-09-17 23:13:52 +0200149 with open(file=os.path.join(json_directory, jsondriver_list),
150 mode='r',
151 encoding='UTF-8') as driver_list_file:
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200152 driver_list = json.load(driver_list_file)
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200153
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200154 return [load_driver(schemas=driver_schema,
155 driver_file=os.path.join(json_directory, driver_file_name))
156 for driver_file_name in driver_list]
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200157
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200158
159def trace_exception(e, file=sys.stderr):
160 print("Exception: type: %s, message: %s, trace: %s" % (
161 e.__class__, str(e), format_tb(e.__traceback__)
162 ), file)
Archanae829cd62021-12-24 12:50:36 +0530163
164
Archanae03960e2021-12-19 09:17:04 +0530165def main() -> int:
166 """
167 Main with command line arguments.
Archanafdbbcba2022-02-27 05:38:55 +0530168 returns 1 when read_driver_descriptions returns False
Archanae03960e2021-12-19 09:17:04 +0530169 """
Archana4a9e0262021-12-19 13:34:30 +0530170 def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
Archana4a9e0262021-12-19 13:34:30 +0530171
Archanae03960e2021-12-19 09:17:04 +0530172 parser = argparse.ArgumentParser()
Archana22c78272022-04-11 10:12:08 +0530173 parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
Archanae03960e2021-12-19 09:17:04 +0530174 help='root directory of mbedtls source code')
Archana22c78272022-04-11 10:12:08 +0530175 parser.add_argument('--template-dir',
176 help='directory holding the driver templates')
177 parser.add_argument('--json-dir',
178 help='directory holding the driver JSONs')
Archana01aa39e2022-03-14 15:29:00 +0530179 parser.add_argument('output_directory', nargs='?',
180 help='output file\'s location')
Archanae03960e2021-12-19 09:17:04 +0530181 args = parser.parse_args()
Archana4a9e0262021-12-19 13:34:30 +0530182
Archana31438052022-01-09 15:01:20 +0530183 mbedtls_root = os.path.abspath(args.mbedtls_root)
Archana01aa39e2022-03-14 15:29:00 +0530184
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200185 output_directory = args.output_directory if args.output_directory is not None else \
186 os.path.join(mbedtls_root, 'library')
187 template_directory = args.template_dir if args.template_dir is not None else \
188 os.path.join(mbedtls_root,
189 'scripts',
190 'data_files',
191 'driver_templates')
192 json_directory = args.json_dir if args.json_dir is not None else \
193 os.path.join(mbedtls_root,
194 'scripts',
195 'data_files',
196 'driver_jsons')
Archanae03960e2021-12-19 09:17:04 +0530197
Asfandyar Orakzaide088032022-09-17 22:07:58 +0200198 try:
199 # Read and validate list of driver jsons from driverlist.json
200 merged_driver_json = read_driver_descriptions(mbedtls_root,
201 json_directory,
202 'driverlist.json')
203 except DriverReaderException as e:
204 trace_exception(e)
Archanae829cd62021-12-24 12:50:36 +0530205 return 1
Archanafdbbcba2022-02-27 05:38:55 +0530206 generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
Archanae03960e2021-12-19 09:17:04 +0530207 return 0
208
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200209
Archanae03960e2021-12-19 09:17:04 +0530210if __name__ == '__main__':
211 sys.exit(main())