blob: 97e8bfdeacb9e71f4e5be5906dd58da9af85f932 [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
4 This module is invoked by the build sripts to auto generate the
5 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 Orakzai08f397a2022-09-15 14:25:37 +020026from typing import Tuple, NewType, Dict, Any
Archanae03960e2021-12-19 09:17:04 +053027import argparse
Archana31438052022-01-09 15:01:20 +053028import jsonschema
Archana1f1a34a2021-11-17 08:44:07 +053029import jinja2
Archanae03960e2021-12-19 09:17:04 +053030from mbedtls_dev import build_tree
Archana1f1a34a2021-11-17 08:44:07 +053031
Archanafdbbcba2022-02-27 05:38:55 +053032JSONSchema = NewType('JSONSchema', object)
Archanaa78dc702022-03-13 17:57:45 +053033# The Driver is an Object, but practically it's indexable and can called a dictionary to
34# keep MyPy happy till MyPy comes with a more composite type for JsonObjects.
35Driver = NewType('Driver', dict)
Archanafdbbcba2022-02-27 05:38:55 +053036
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +020037
38class JsonValidationException(Exception):
39 def __init__(self, message="Json Validation Failed"):
40 self.message = message
41 super().__init__(self.message)
42
43
Archanae829cd62021-12-24 12:50:36 +053044def render(template_path: str, driver_jsoncontext: list) -> str:
Archanae03960e2021-12-19 09:17:04 +053045 """
Archanae829cd62021-12-24 12:50:36 +053046 Render template from the input file and driver JSON.
Archanae03960e2021-12-19 09:17:04 +053047 """
Archana6f21e452021-11-23 14:46:51 +053048 environment = jinja2.Environment(
49 loader=jinja2.FileSystemLoader(os.path.dirname(template_path)),
50 keep_trailing_newline=True)
51 template = environment.get_template(os.path.basename(template_path))
Archanae03960e2021-12-19 09:17:04 +053052
Archana31438052022-01-09 15:01:20 +053053 return template.render(drivers=driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053054
Archanae829cd62021-12-24 12:50:36 +053055
Archana31438052022-01-09 15:01:20 +053056def generate_driver_wrapper_file(template_dir: str, \
57 output_dir: str, driver_jsoncontext: list) -> None:
Archanae03960e2021-12-19 09:17:04 +053058 """
59 Generate the file psa_crypto_driver_wrapper.c.
60 """
61 driver_wrapper_template_filename = \
Archanae829cd62021-12-24 12:50:36 +053062 os.path.join(template_dir, "psa_crypto_driver_wrappers.c.jinja")
Archana1f1a34a2021-11-17 08:44:07 +053063
Archanae829cd62021-12-24 12:50:36 +053064 result = render(driver_wrapper_template_filename, driver_jsoncontext)
Archana1f1a34a2021-11-17 08:44:07 +053065
Archanae03960e2021-12-19 09:17:04 +053066 with open(os.path.join(output_dir, "psa_crypto_driver_wrappers.c"), 'w') as out_file:
67 out_file.write(result)
Archana6f21e452021-11-23 14:46:51 +053068
Archanae829cd62021-12-24 12:50:36 +053069
Archanafdbbcba2022-02-27 05:38:55 +053070def validate_json(driverjson_data: Driver, driverschema_list: dict) -> bool:
Archanae829cd62021-12-24 12:50:36 +053071 """
Archanafdbbcba2022-02-27 05:38:55 +053072 Validate the Driver JSON against an appropriate schema
73 the schema passed could be that matching an opaque/ transparent driver.
Archana04cfe342022-01-09 13:28:28 +053074 """
Archanafdbbcba2022-02-27 05:38:55 +053075 driver_type = driverjson_data["type"]
76 driver_prefix = driverjson_data["prefix"]
Archana04cfe342022-01-09 13:28:28 +053077 try:
Archanafdbbcba2022-02-27 05:38:55 +053078 _schema = driverschema_list[driver_type]
79 jsonschema.validate(instance=driverjson_data, schema=_schema)
80
81 except KeyError as err:
82 # This could happen if the driverjson_data.type does not exist in the passed in schema list
83 # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
84 # Print onto stdout and stderr.
85 print("Unknown Driver type " + driver_type +
86 " for driver " + driver_prefix, str(err))
87 print("Unknown Driver type " + driver_type +
88 " for driver " + driver_prefix, str(err), file=sys.stderr)
89 return False
90
Archana04cfe342022-01-09 13:28:28 +053091 except jsonschema.exceptions.ValidationError as err:
Archanafdbbcba2022-02-27 05:38:55 +053092 # Print onto stdout and stderr.
93 print("Error: Failed to validate data file: {} using schema: {}."
94 "\n Exception Message: \"{}\""
95 " ".format(driverjson_data, _schema, str(err)))
96 print("Error: Failed to validate data file: {} using schema: {}."
97 "\n Exception Message: \"{}\""
98 " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
Archana04cfe342022-01-09 13:28:28 +053099 return False
100
Archana04cfe342022-01-09 13:28:28 +0530101 return True
102
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200103
104def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
105 with open(driver_file, 'r') as f:
106 json_data = json.load(f)
107 if not validate_json(json_data, schemas):
108 raise JsonValidationException()
109 return json_data
110
111
Archanafdbbcba2022-02-27 05:38:55 +0530112def read_driver_descriptions(mbedtls_root: str, json_directory: str, \
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200113 jsondriver_list: str) -> Tuple[bool, list]:
Archana04cfe342022-01-09 13:28:28 +0530114 """
115 Merge driver JSON files into a single ordered JSON after validation.
Archanae829cd62021-12-24 12:50:36 +0530116 """
Archanafdbbcba2022-02-27 05:38:55 +0530117 result = []
118 with open(os.path.join(mbedtls_root,
119 'scripts',
120 'data_files',
121 'driver_jsons',
122 'driver_transparent_schema.json'), 'r') as file:
Archana04cfe342022-01-09 13:28:28 +0530123 transparent_driver_schema = json.load(file)
Archanafdbbcba2022-02-27 05:38:55 +0530124 with open(os.path.join(mbedtls_root,
125 'scripts',
126 'data_files',
127 'driver_jsons',
128 'driver_opaque_schema.json'), 'r') as file:
Archana04cfe342022-01-09 13:28:28 +0530129 opaque_driver_schema = json.load(file)
130
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200131 driver_schema = {'transparent': transparent_driver_schema,
132 'opaque': opaque_driver_schema}
Archana31438052022-01-09 15:01:20 +0530133 with open(os.path.join(json_directory, jsondriver_list), 'r') as driverlistfile:
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200134 driver_list = json.load(driverlistfile)
135
136 try:
137 result = [load_driver(driver_schema, driver_file=os.path.join(json_directory, driver_file_name))
138 for driver_file_name in driver_list]
139 except JsonValidationException as _:
140 return False, []
141
Archana04cfe342022-01-09 13:28:28 +0530142 return True, result
Archanae829cd62021-12-24 12:50:36 +0530143
144
Archanae03960e2021-12-19 09:17:04 +0530145def main() -> int:
146 """
147 Main with command line arguments.
Archanafdbbcba2022-02-27 05:38:55 +0530148 returns 1 when read_driver_descriptions returns False
Archanae03960e2021-12-19 09:17:04 +0530149 """
Archana4a9e0262021-12-19 13:34:30 +0530150 def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
Archana4a9e0262021-12-19 13:34:30 +0530151
Archanae03960e2021-12-19 09:17:04 +0530152 parser = argparse.ArgumentParser()
Archana22c78272022-04-11 10:12:08 +0530153 parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
Archanae03960e2021-12-19 09:17:04 +0530154 help='root directory of mbedtls source code')
Archana22c78272022-04-11 10:12:08 +0530155 parser.add_argument('--template-dir',
156 help='directory holding the driver templates')
157 parser.add_argument('--json-dir',
158 help='directory holding the driver JSONs')
Archana01aa39e2022-03-14 15:29:00 +0530159 parser.add_argument('output_directory', nargs='?',
160 help='output file\'s location')
Archanae03960e2021-12-19 09:17:04 +0530161 args = parser.parse_args()
Archana4a9e0262021-12-19 13:34:30 +0530162
Archana31438052022-01-09 15:01:20 +0530163 mbedtls_root = os.path.abspath(args.mbedtls_root)
Archanafdbbcba2022-02-27 05:38:55 +0530164 if args.template_dir is None:
Archana01aa39e2022-03-14 15:29:00 +0530165 args.template_dir = os.path.join(mbedtls_root,
166 'scripts',
167 'data_files',
168 'driver_templates')
Archanafdbbcba2022-02-27 05:38:55 +0530169 if args.json_dir is None:
Archana01aa39e2022-03-14 15:29:00 +0530170 args.json_dir = os.path.join(mbedtls_root,
171 'scripts',
172 'data_files',
173 'driver_jsons')
174 if args.output_directory is None:
175 args.output_directory = os.path.join(mbedtls_root, 'library')
176
177 output_directory = args.output_directory
178 template_directory = args.template_dir
Archana31438052022-01-09 15:01:20 +0530179 json_directory = args.json_dir
Archanae03960e2021-12-19 09:17:04 +0530180
Archanafdbbcba2022-02-27 05:38:55 +0530181 # Read and validate list of driver jsons from driverlist.json
182 ret, merged_driver_json = read_driver_descriptions(mbedtls_root, json_directory,
183 'driverlist.json')
Archana31438052022-01-09 15:01:20 +0530184 if ret is False:
Archanae829cd62021-12-24 12:50:36 +0530185 return 1
Archanafdbbcba2022-02-27 05:38:55 +0530186 generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
Archanae03960e2021-12-19 09:17:04 +0530187
188 return 0
189
Asfandyar Orakzai08f397a2022-09-15 14:25:37 +0200190
Archanae03960e2021-12-19 09:17:04 +0530191if __name__ == '__main__':
192 sys.exit(main())