blob: 9bb6eb758b328d0fa8d661cfc981db388cc2cb2c [file] [log] [blame]
Gilles Peskine5294bb32024-01-04 16:38:17 +01001#!/usr/bin/env python3
2"""Generate wrapper functions for PSA function calls.
3"""
4
5# Copyright The Mbed TLS Contributors
6# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7
8import argparse
9import os
10from typing import List, Tuple
11
12import scripts_path #pylint: disable=unused-import
13from mbedtls_dev import build_tree
14from mbedtls_dev import c_parsing_helper
15from mbedtls_dev import c_wrapper_generator
16from mbedtls_dev import typing_util
17
18
19class PSAWrapperGenerator(c_wrapper_generator.Base):
20 """Generate a C source file containing wrapper functions for PSA Crypto API calls."""
21
22 _CPP_GUARDS = 'defined(MBEDTLS_PSA_CRYPTO_C) && defined(MBEDTLS_TEST_HOOKS)'
23 _WRAPPER_NAME_PREFIX = 'mbedtls_test_wrap_'
24 _WRAPPER_NAME_SUFFIX = ''
25
26 def gather_data(self) -> None:
27 root_dir = build_tree.guess_mbedtls_root()
28 for header_name in ['crypto.h', 'crypto_extra.h']:
29 header_path = os.path.join(root_dir, 'include', 'psa', header_name)
30 c_parsing_helper.read_function_declarations(self.functions, header_path)
31
32 _SKIP_FUNCTIONS = frozenset([
33 'mbedtls_psa_external_get_random', # not a library function
34 'psa_get_key_domain_parameters', # client-side function
35 'psa_get_key_slot_number', # client-side function
36 'psa_key_derivation_verify_bytes', # not implemented yet
37 'psa_key_derivation_verify_key', # not implemented yet
38 'psa_set_key_domain_parameters', # client-side function
39 ])
40
41 def _skip_function(self, function: c_wrapper_generator.FunctionInfo) -> bool:
42 if function.return_type != 'psa_status_t':
43 return True
44 if function.name in self._SKIP_FUNCTIONS:
45 return True
46 return False
47
48 # PAKE stuff: not implemented yet
49 _PAKE_STUFF = frozenset([
50 'psa_crypto_driver_pake_inputs_t *',
51 'psa_pake_cipher_suite_t *',
52 ])
53
54 def _return_variable_name(self,
55 function: c_wrapper_generator.FunctionInfo) -> str:
56 """The name of the variable that will contain the return value."""
57 if function.return_type == 'psa_status_t':
58 return 'status'
59 return super()._return_variable_name(function)
60
61 _FUNCTION_GUARDS = c_wrapper_generator.Base._FUNCTION_GUARDS.copy() \
62 #pylint: disable=protected-access
63 _FUNCTION_GUARDS.update({
64 'mbedtls_psa_register_se_key': 'defined(MBEDTLS_PSA_CRYPTO_SE_C)',
65 'mbedtls_psa_inject_entropy': 'defined(MBEDTLS_PSA_INJECT_ENTROPY)',
66 'mbedtls_psa_external_get_random': 'defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)',
67 'mbedtls_psa_platform_get_builtin_key': 'defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)',
68 })
69
70 def _write_prologue(self, out: typing_util.Writable, header: bool) -> None:
71 super()._write_prologue(out, header)
72 out.write("""
73#if {}
74
75#include <psa/crypto.h>
76
77#include <test/psa_crypto_helpers.h>
78#include <test/psa_test_wrappers.h>
79"""
80 .format(self._CPP_GUARDS))
81
82 def _write_epilogue(self, out: typing_util.Writable, header: bool) -> None:
83 out.write("""
84#endif /* {} */
85"""
86 .format(self._CPP_GUARDS))
87 super()._write_epilogue(out, header)
88
89
90class PSALoggingWrapperGenerator(PSAWrapperGenerator, c_wrapper_generator.Logging):
91 """Generate a C source file containing wrapper functions that log PSA Crypto API calls."""
92
93 def __init__(self, stream: str) -> None:
94 super().__init__()
95 self.set_stream(stream)
96
97 _PRINTF_TYPE_CAST = c_wrapper_generator.Logging._PRINTF_TYPE_CAST.copy()
98 _PRINTF_TYPE_CAST.update({
99 'mbedtls_svc_key_id_t': 'unsigned',
100 'psa_algorithm_t': 'unsigned',
101 'psa_drv_slot_number_t': 'unsigned long long',
102 'psa_key_derivation_step_t': 'int',
103 'psa_key_id_t': 'unsigned',
104 'psa_key_slot_number_t': 'unsigned long long',
105 'psa_key_lifetime_t': 'unsigned',
106 'psa_key_type_t': 'unsigned',
107 'psa_key_usage_flags_t': 'unsigned',
108 'psa_pake_role_t': 'int',
109 'psa_pake_step_t': 'int',
110 'psa_status_t': 'int',
111 })
112
113 def _printf_parameters(self, typ: str, var: str) -> Tuple[str, List[str]]:
114 if typ.startswith('const '):
115 typ = typ[6:]
116 if typ == 'uint8_t *':
117 # Skip buffers
118 return '', []
119 if typ.endswith('operation_t *'):
120 return '', []
121 if typ in self._PAKE_STUFF:
122 return '', []
123 if typ == 'psa_key_attributes_t *':
124 return (var + '={id=%u, lifetime=0x%08x, type=0x%08x, bits=%u, alg=%08x, usage=%08x}',
125 ['(unsigned) psa_get_key_{}({})'.format(field, var)
126 for field in ['id', 'lifetime', 'type', 'bits', 'algorithm', 'usage_flags']])
127 return super()._printf_parameters(typ, var)
128
129
130DEFAULT_C_OUTPUT_FILE_NAME = 'tests/src/psa_test_wrappers.c'
131DEFAULT_H_OUTPUT_FILE_NAME = 'tests/include/test/psa_test_wrappers.h'
132
133def main() -> None:
134 parser = argparse.ArgumentParser(description=globals()['__doc__'])
135 parser.add_argument('--log',
136 help='Stream to log to (default: no logging code)')
137 parser.add_argument('--output-c',
138 metavar='FILENAME',
139 default=DEFAULT_C_OUTPUT_FILE_NAME,
140 help=('Output .c file path (default: {}; skip .c output if empty)'
141 .format(DEFAULT_C_OUTPUT_FILE_NAME)))
142 parser.add_argument('--output-h',
143 metavar='FILENAME',
144 default=DEFAULT_H_OUTPUT_FILE_NAME,
145 help=('Output .h file path (default: {}; skip .h output if empty)'
146 .format(DEFAULT_H_OUTPUT_FILE_NAME)))
147 options = parser.parse_args()
148 if options.log:
149 generator = PSALoggingWrapperGenerator(options.log) #type: PSAWrapperGenerator
150 else:
151 generator = PSAWrapperGenerator()
152 generator.gather_data()
153 if options.output_h:
154 generator.write_h_file(options.output_h)
155 if options.output_c:
156 generator.write_c_file(options.output_c)
157
158if __name__ == '__main__':
159 main()