generate_driver_wrappers.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python3
  2. """Generate library/psa_crypto_driver_wrappers.c
  3. This module is invoked by the build scripts to auto generate the
  4. psa_crypto_driver_wrappers.c based on template files in
  5. script/data_files/driver_templates/.
  6. """
  7. # Copyright The Mbed TLS Contributors
  8. # SPDX-License-Identifier: Apache-2.0
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  11. # not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  18. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. import sys
  22. import os
  23. import json
  24. from typing import NewType, Dict, Any
  25. from traceback import format_tb
  26. import argparse
  27. import jsonschema
  28. import jinja2
  29. from mbedtls_dev import build_tree
  30. JSONSchema = NewType('JSONSchema', object)
  31. # The Driver is an Object, but practically it's indexable and can called a dictionary to
  32. # keep MyPy happy till MyPy comes with a more composite type for JsonObjects.
  33. Driver = NewType('Driver', dict)
  34. class JsonValidationException(Exception):
  35. def __init__(self, message="Json Validation Failed"):
  36. self.message = message
  37. super().__init__(self.message)
  38. class DriverReaderException(Exception):
  39. def __init__(self, message="Driver Reader Failed"):
  40. self.message = message
  41. super().__init__(self.message)
  42. def render(template_path: str, driver_jsoncontext: list) -> str:
  43. """
  44. Render template from the input file and driver JSON.
  45. """
  46. environment = jinja2.Environment(
  47. loader=jinja2.FileSystemLoader(os.path.dirname(template_path)),
  48. keep_trailing_newline=True)
  49. template = environment.get_template(os.path.basename(template_path))
  50. return template.render(drivers=driver_jsoncontext)
  51. def generate_driver_wrapper_file(template_dir: str,
  52. output_dir: str,
  53. driver_jsoncontext: list) -> None:
  54. """
  55. Generate the file psa_crypto_driver_wrapper.c.
  56. """
  57. driver_wrapper_template_filename = \
  58. os.path.join(template_dir, "psa_crypto_driver_wrappers.c.jinja")
  59. result = render(driver_wrapper_template_filename, driver_jsoncontext)
  60. with open(file=os.path.join(output_dir, "psa_crypto_driver_wrappers.c"),
  61. mode='w',
  62. encoding='UTF-8') as out_file:
  63. out_file.write(result)
  64. def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
  65. """
  66. Validate the Driver JSON against an appropriate schema
  67. the schema passed could be that matching an opaque/ transparent driver.
  68. """
  69. driver_type = driverjson_data["type"]
  70. driver_prefix = driverjson_data["prefix"]
  71. try:
  72. _schema = driverschema_list[driver_type]
  73. jsonschema.validate(instance=driverjson_data, schema=_schema)
  74. except KeyError as err:
  75. # This could happen if the driverjson_data.type does not exist in the provided schema list
  76. # schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
  77. # Print onto stdout and stderr.
  78. print("Unknown Driver type " + driver_type +
  79. " for driver " + driver_prefix, str(err))
  80. print("Unknown Driver type " + driver_type +
  81. " for driver " + driver_prefix, str(err), file=sys.stderr)
  82. raise JsonValidationException() from err
  83. except jsonschema.exceptions.ValidationError as err:
  84. # Print onto stdout and stderr.
  85. print("Error: Failed to validate data file: {} using schema: {}."
  86. "\n Exception Message: \"{}\""
  87. " ".format(driverjson_data, _schema, str(err)))
  88. print("Error: Failed to validate data file: {} using schema: {}."
  89. "\n Exception Message: \"{}\""
  90. " ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
  91. raise JsonValidationException() from err
  92. def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
  93. """loads validated json driver"""
  94. with open(file=driver_file, mode='r', encoding='UTF-8') as f:
  95. json_data = json.load(f)
  96. try:
  97. validate_json(json_data, schemas)
  98. except JsonValidationException as e:
  99. raise DriverReaderException from e
  100. return json_data
  101. def load_schemas(mbedtls_root: str) -> Dict[str, Any]:
  102. """
  103. Load schemas map
  104. """
  105. schema_file_paths = {
  106. 'transparent': os.path.join(mbedtls_root,
  107. 'scripts',
  108. 'data_files',
  109. 'driver_jsons',
  110. 'driver_transparent_schema.json'),
  111. 'opaque': os.path.join(mbedtls_root,
  112. 'scripts',
  113. 'data_files',
  114. 'driver_jsons',
  115. 'driver_opaque_schema.json')
  116. }
  117. driver_schema = {}
  118. for key, file_path in schema_file_paths.items():
  119. with open(file=file_path, mode='r', encoding='UTF-8') as file:
  120. driver_schema[key] = json.load(file)
  121. return driver_schema
  122. def read_driver_descriptions(mbedtls_root: str,
  123. json_directory: str,
  124. jsondriver_list: str) -> list:
  125. """
  126. Merge driver JSON files into a single ordered JSON after validation.
  127. """
  128. driver_schema = load_schemas(mbedtls_root)
  129. with open(file=os.path.join(json_directory, jsondriver_list),
  130. mode='r',
  131. encoding='UTF-8') as driver_list_file:
  132. driver_list = json.load(driver_list_file)
  133. return [load_driver(schemas=driver_schema,
  134. driver_file=os.path.join(json_directory, driver_file_name))
  135. for driver_file_name in driver_list]
  136. def trace_exception(e: Exception, file=sys.stderr) -> None:
  137. """Prints exception trace to the given TextIO handle"""
  138. print("Exception: type: %s, message: %s, trace: %s" % (
  139. e.__class__, str(e), format_tb(e.__traceback__)
  140. ), file)
  141. def main() -> int:
  142. """
  143. Main with command line arguments.
  144. """
  145. def_arg_mbedtls_root = build_tree.guess_mbedtls_root()
  146. parser = argparse.ArgumentParser()
  147. parser.add_argument('--mbedtls-root', default=def_arg_mbedtls_root,
  148. help='root directory of mbedtls source code')
  149. parser.add_argument('--template-dir',
  150. help='directory holding the driver templates')
  151. parser.add_argument('--json-dir',
  152. help='directory holding the driver JSONs')
  153. parser.add_argument('output_directory', nargs='?',
  154. help='output file\'s location')
  155. args = parser.parse_args()
  156. mbedtls_root = os.path.abspath(args.mbedtls_root)
  157. output_directory = args.output_directory if args.output_directory is not None else \
  158. os.path.join(mbedtls_root, 'library')
  159. template_directory = args.template_dir if args.template_dir is not None else \
  160. os.path.join(mbedtls_root,
  161. 'scripts',
  162. 'data_files',
  163. 'driver_templates')
  164. json_directory = args.json_dir if args.json_dir is not None else \
  165. os.path.join(mbedtls_root,
  166. 'scripts',
  167. 'data_files',
  168. 'driver_jsons')
  169. try:
  170. # Read and validate list of driver jsons from driverlist.json
  171. merged_driver_json = read_driver_descriptions(mbedtls_root,
  172. json_directory,
  173. 'driverlist.json')
  174. except DriverReaderException as e:
  175. trace_exception(e)
  176. return 1
  177. generate_driver_wrapper_file(template_directory, output_directory, merged_driver_json)
  178. return 0
  179. if __name__ == '__main__':
  180. sys.exit(main())