blob: 537f9e94eb3bb82c226a6524e10c27a904025e4a [file] [log] [blame]
Gilles Peskine24827022018-09-25 18:49:23 +02001#!/usr/bin/env python3
Gilles Peskinea3b93ff2019-06-03 11:23:56 +02002"""Test the program psa_constant_names.
Gilles Peskine24827022018-09-25 18:49:23 +02003Gather constant names from header files and test cases. Compile a C program
4to print out their numerical values, feed these numerical values to
5psa_constant_names, and check that the output is the original name.
6Return 0 if all test cases pass, 1 if the output was not always as expected,
Gilles Peskinea3b93ff2019-06-03 11:23:56 +02007or 1 (with a Python backtrace) if there was an operational error.
8"""
Gilles Peskine24827022018-09-25 18:49:23 +02009
Bence Szépkúti1e148272020-08-07 13:07:28 +020010# Copyright The Mbed TLS Contributors
Bence Szépkútic7da1fe2020-05-26 01:54:15 +020011# SPDX-License-Identifier: Apache-2.0
12#
13# Licensed under the Apache License, Version 2.0 (the "License"); you may
14# not use this file except in compliance with the License.
15# You may obtain a copy of the License at
16#
17# http://www.apache.org/licenses/LICENSE-2.0
18#
19# Unless required by applicable law or agreed to in writing, software
20# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
21# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22# See the License for the specific language governing permissions and
23# limitations under the License.
Bence Szépkúti700ee442020-05-26 00:33:31 +020024
Gilles Peskine24827022018-09-25 18:49:23 +020025import argparse
Gilles Peskinea5000f12019-11-21 17:51:11 +010026from collections import namedtuple
Gilles Peskine24827022018-09-25 18:49:23 +020027import itertools
28import os
Gilles Peskine24827022018-09-25 18:49:23 +020029import re
30import subprocess
31import sys
Gilles Peskine2adebc82020-12-11 00:30:53 +010032
33import scripts_path # pylint: disable=unused-import
34from mbedtls_dev import c_build_helper
Gilles Peskine24827022018-09-25 18:49:23 +020035
Gilles Peskinea0a315c2018-10-19 11:27:10 +020036class ReadFileLineException(Exception):
37 def __init__(self, filename, line_number):
38 message = 'in {} at {}'.format(filename, line_number)
39 super(ReadFileLineException, self).__init__(message)
40 self.filename = filename
41 self.line_number = line_number
42
43class read_file_lines:
Gilles Peskine54f54452019-05-27 18:31:59 +020044 # Dear Pylint, conventionally, a context manager class name is lowercase.
45 # pylint: disable=invalid-name,too-few-public-methods
Gilles Peskinea3b93ff2019-06-03 11:23:56 +020046 """Context manager to read a text file line by line.
47
48 ```
49 with read_file_lines(filename) as lines:
50 for line in lines:
51 process(line)
52 ```
53 is equivalent to
54 ```
55 with open(filename, 'r') as input_file:
56 for line in input_file:
57 process(line)
58 ```
59 except that if process(line) raises an exception, then the read_file_lines
60 snippet annotates the exception with the file name and line number.
61 """
Gilles Peskine49af2d32019-12-06 19:20:13 +010062 def __init__(self, filename, binary=False):
Gilles Peskinea0a315c2018-10-19 11:27:10 +020063 self.filename = filename
64 self.line_number = 'entry'
Gilles Peskine54f54452019-05-27 18:31:59 +020065 self.generator = None
Gilles Peskine49af2d32019-12-06 19:20:13 +010066 self.binary = binary
Gilles Peskinea0a315c2018-10-19 11:27:10 +020067 def __enter__(self):
Gilles Peskine49af2d32019-12-06 19:20:13 +010068 self.generator = enumerate(open(self.filename,
69 'rb' if self.binary else 'r'))
Gilles Peskinea0a315c2018-10-19 11:27:10 +020070 return self
71 def __iter__(self):
72 for line_number, content in self.generator:
73 self.line_number = line_number
74 yield content
75 self.line_number = 'exit'
Gilles Peskine42a0a0a2019-05-27 18:29:47 +020076 def __exit__(self, exc_type, exc_value, exc_traceback):
77 if exc_type is not None:
Gilles Peskinea0a315c2018-10-19 11:27:10 +020078 raise ReadFileLineException(self.filename, self.line_number) \
Gilles Peskine42a0a0a2019-05-27 18:29:47 +020079 from exc_value
Gilles Peskinea0a315c2018-10-19 11:27:10 +020080
Gilles Peskine24827022018-09-25 18:49:23 +020081class Inputs:
Gilles Peskine8c8694c2019-11-21 19:22:45 +010082 # pylint: disable=too-many-instance-attributes
Gilles Peskinea3b93ff2019-06-03 11:23:56 +020083 """Accumulate information about macros to test.
Gilles Peskine4408dfd2019-11-21 17:16:21 +010084
Gilles Peskinea3b93ff2019-06-03 11:23:56 +020085 This includes macro names as well as information about their arguments
86 when applicable.
87 """
88
Gilles Peskine24827022018-09-25 18:49:23 +020089 def __init__(self):
Gilles Peskine2bcfc712019-11-21 19:49:26 +010090 self.all_declared = set()
Gilles Peskine24827022018-09-25 18:49:23 +020091 # Sets of names per type
92 self.statuses = set(['PSA_SUCCESS'])
93 self.algorithms = set(['0xffffffff'])
Gilles Peskinef65ed6f2019-12-04 17:18:41 +010094 self.ecc_curves = set(['0xff'])
95 self.dh_groups = set(['0xff'])
96 self.key_types = set(['0xffff'])
Gilles Peskine24827022018-09-25 18:49:23 +020097 self.key_usage_flags = set(['0x80000000'])
Bence Szépkúti4af65602020-12-08 11:10:21 +010098 # Hard-coded values for unknown algorithms
99 #
100 # These have to have values that are correct for their respective
101 # PSA_ALG_IS_xxx macros, but are also not currently assigned and are
102 # not likely to be assigned in the near future.
103 self.hash_algorithms = set(['0x020000fe']) # 0x020000ff is PSA_ALG_ANY_HASH
Bence Szépkúti7e37bf92020-12-08 07:33:08 +0100104 self.mac_algorithms = set(['0x0300ffff'])
105 self.ka_algorithms = set(['0x09fc0000'])
106 self.kdf_algorithms = set(['0x080000ff'])
Gilles Peskine434899f2018-10-19 11:30:26 +0200107 # For AEAD algorithms, the only variability is over the tag length,
108 # and this only applies to known algorithms, so don't test an
109 # unknown algorithm.
110 self.aead_algorithms = set()
Gilles Peskine24827022018-09-25 18:49:23 +0200111 # Identifier prefixes
112 self.table_by_prefix = {
113 'ERROR': self.statuses,
114 'ALG': self.algorithms,
Gilles Peskine98a710c2019-11-21 18:58:36 +0100115 'ECC_CURVE': self.ecc_curves,
116 'DH_GROUP': self.dh_groups,
Gilles Peskine24827022018-09-25 18:49:23 +0200117 'KEY_TYPE': self.key_types,
118 'KEY_USAGE': self.key_usage_flags,
119 }
Gilles Peskine8c8694c2019-11-21 19:22:45 +0100120 # Test functions
121 self.table_by_test_function = {
Gilles Peskine8fa13482019-11-25 17:10:12 +0100122 # Any function ending in _algorithm also gets added to
123 # self.algorithms.
124 'key_type': [self.key_types],
Gilles Peskinef8210f22019-12-02 17:26:44 +0100125 'block_cipher_key_type': [self.key_types],
126 'stream_cipher_key_type': [self.key_types],
Gilles Peskine228abc52019-12-03 17:24:19 +0100127 'ecc_key_family': [self.ecc_curves],
Gilles Peskine8fa13482019-11-25 17:10:12 +0100128 'ecc_key_types': [self.ecc_curves],
Gilles Peskine228abc52019-12-03 17:24:19 +0100129 'dh_key_family': [self.dh_groups],
Gilles Peskine8fa13482019-11-25 17:10:12 +0100130 'dh_key_types': [self.dh_groups],
131 'hash_algorithm': [self.hash_algorithms],
132 'mac_algorithm': [self.mac_algorithms],
133 'cipher_algorithm': [],
134 'hmac_algorithm': [self.mac_algorithms],
135 'aead_algorithm': [self.aead_algorithms],
136 'key_derivation_algorithm': [self.kdf_algorithms],
137 'key_agreement_algorithm': [self.ka_algorithms],
138 'asymmetric_signature_algorithm': [],
139 'asymmetric_signature_wildcard': [self.algorithms],
140 'asymmetric_encryption_algorithm': [],
141 'other_algorithm': [],
Gilles Peskine8c8694c2019-11-21 19:22:45 +0100142 }
Gilles Peskine24827022018-09-25 18:49:23 +0200143 # macro name -> list of argument names
144 self.argspecs = {}
145 # argument name -> list of values
Gilles Peskine434899f2018-10-19 11:30:26 +0200146 self.arguments_for = {
147 'mac_length': ['1', '63'],
148 'tag_length': ['1', '63'],
149 }
Gilles Peskine24827022018-09-25 18:49:23 +0200150
Gilles Peskineffe2d6e2019-11-21 17:17:01 +0100151 def get_names(self, type_word):
152 """Return the set of known names of values of the given type."""
153 return {
154 'status': self.statuses,
155 'algorithm': self.algorithms,
156 'ecc_curve': self.ecc_curves,
157 'dh_group': self.dh_groups,
158 'key_type': self.key_types,
159 'key_usage': self.key_usage_flags,
160 }[type_word]
161
Gilles Peskine24827022018-09-25 18:49:23 +0200162 def gather_arguments(self):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200163 """Populate the list of values for macro arguments.
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100164
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200165 Call this after parsing all the inputs.
166 """
Gilles Peskine24827022018-09-25 18:49:23 +0200167 self.arguments_for['hash_alg'] = sorted(self.hash_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +0200168 self.arguments_for['mac_alg'] = sorted(self.mac_algorithms)
Gilles Peskine882e57e2019-04-12 00:12:07 +0200169 self.arguments_for['ka_alg'] = sorted(self.ka_algorithms)
Gilles Peskine17542082019-01-04 19:46:31 +0100170 self.arguments_for['kdf_alg'] = sorted(self.kdf_algorithms)
Gilles Peskine434899f2018-10-19 11:30:26 +0200171 self.arguments_for['aead_alg'] = sorted(self.aead_algorithms)
Gilles Peskine24827022018-09-25 18:49:23 +0200172 self.arguments_for['curve'] = sorted(self.ecc_curves)
Gilles Peskinedcaefae2019-05-16 12:55:35 +0200173 self.arguments_for['group'] = sorted(self.dh_groups)
Gilles Peskine24827022018-09-25 18:49:23 +0200174
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200175 @staticmethod
176 def _format_arguments(name, arguments):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200177 """Format a macro call with arguments.."""
Gilles Peskine24827022018-09-25 18:49:23 +0200178 return name + '(' + ', '.join(arguments) + ')'
179
180 def distribute_arguments(self, name):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200181 """Generate macro calls with each tested argument set.
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100182
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200183 If name is a macro without arguments, just yield "name".
184 If name is a macro with arguments, yield a series of
185 "name(arg1,...,argN)" where each argument takes each possible
186 value at least once.
187 """
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200188 try:
189 if name not in self.argspecs:
190 yield name
191 return
192 argspec = self.argspecs[name]
193 if argspec == []:
194 yield name + '()'
195 return
196 argument_lists = [self.arguments_for[arg] for arg in argspec]
197 arguments = [values[0] for values in argument_lists]
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200198 yield self._format_arguments(name, arguments)
Gilles Peskine54f54452019-05-27 18:31:59 +0200199 # Dear Pylint, enumerate won't work here since we're modifying
200 # the array.
201 # pylint: disable=consider-using-enumerate
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200202 for i in range(len(arguments)):
203 for value in argument_lists[i][1:]:
204 arguments[i] = value
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200205 yield self._format_arguments(name, arguments)
Gilles Peskinef96ed662018-10-19 11:29:56 +0200206 arguments[i] = argument_lists[0][0]
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200207 except BaseException as e:
208 raise Exception('distribute_arguments({})'.format(name)) from e
Gilles Peskine24827022018-09-25 18:49:23 +0200209
Gilles Peskine5a994c12019-11-21 16:46:51 +0100210 def generate_expressions(self, names):
211 return itertools.chain(*map(self.distribute_arguments, names))
212
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200213 _argument_split_re = re.compile(r' *, *')
214 @classmethod
215 def _argument_split(cls, arguments):
216 return re.split(cls._argument_split_re, arguments)
217
Gilles Peskine24827022018-09-25 18:49:23 +0200218 # Regex for interesting header lines.
219 # Groups: 1=macro name, 2=type, 3=argument list (optional).
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200220 _header_line_re = \
Gilles Peskine24827022018-09-25 18:49:23 +0200221 re.compile(r'#define +' +
Gilles Peskine98a710c2019-11-21 18:58:36 +0100222 r'(PSA_((?:(?:DH|ECC|KEY)_)?[A-Z]+)_\w+)' +
Gilles Peskine24827022018-09-25 18:49:23 +0200223 r'(?:\(([^\n()]*)\))?')
224 # Regex of macro names to exclude.
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200225 _excluded_name_re = re.compile(r'_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
Gilles Peskinec68ce962018-10-19 11:31:52 +0200226 # Additional excluded macros.
Gilles Peskine5c196fb2019-05-17 12:04:41 +0200227 _excluded_names = set([
228 # Macros that provide an alternative way to build the same
229 # algorithm as another macro.
Bence Szépkútia63b20d2020-12-16 11:36:46 +0100230 'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG',
Gilles Peskine5c196fb2019-05-17 12:04:41 +0200231 'PSA_ALG_FULL_LENGTH_MAC',
232 # Auxiliary macro whose name doesn't fit the usual patterns for
233 # auxiliary macros.
Bence Szépkútia63b20d2020-12-16 11:36:46 +0100234 'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE',
Gilles Peskine5c196fb2019-05-17 12:04:41 +0200235 ])
Gilles Peskine24827022018-09-25 18:49:23 +0200236 def parse_header_line(self, line):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200237 """Parse a C header line, looking for "#define PSA_xxx"."""
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200238 m = re.match(self._header_line_re, line)
Gilles Peskine24827022018-09-25 18:49:23 +0200239 if not m:
240 return
241 name = m.group(1)
Gilles Peskine2bcfc712019-11-21 19:49:26 +0100242 self.all_declared.add(name)
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200243 if re.search(self._excluded_name_re, name) or \
244 name in self._excluded_names:
Gilles Peskine24827022018-09-25 18:49:23 +0200245 return
246 dest = self.table_by_prefix.get(m.group(2))
247 if dest is None:
248 return
249 dest.add(name)
250 if m.group(3):
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200251 self.argspecs[name] = self._argument_split(m.group(3))
Gilles Peskine24827022018-09-25 18:49:23 +0200252
Gilles Peskine49af2d32019-12-06 19:20:13 +0100253 _nonascii_re = re.compile(rb'[^\x00-\x7f]+')
Gilles Peskine24827022018-09-25 18:49:23 +0200254 def parse_header(self, filename):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200255 """Parse a C header file, looking for "#define PSA_xxx"."""
Gilles Peskine49af2d32019-12-06 19:20:13 +0100256 with read_file_lines(filename, binary=True) as lines:
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200257 for line in lines:
Gilles Peskine49af2d32019-12-06 19:20:13 +0100258 line = re.sub(self._nonascii_re, rb'', line).decode('ascii')
Gilles Peskine24827022018-09-25 18:49:23 +0200259 self.parse_header_line(line)
260
Gilles Peskine49af2d32019-12-06 19:20:13 +0100261 _macro_identifier_re = re.compile(r'[A-Z]\w+')
Gilles Peskine2bcfc712019-11-21 19:49:26 +0100262 def generate_undeclared_names(self, expr):
263 for name in re.findall(self._macro_identifier_re, expr):
264 if name not in self.all_declared:
265 yield name
266
267 def accept_test_case_line(self, function, argument):
268 #pylint: disable=unused-argument
269 undeclared = list(self.generate_undeclared_names(argument))
270 if undeclared:
271 raise Exception('Undeclared names in test case', undeclared)
272 return True
273
Gilles Peskine24827022018-09-25 18:49:23 +0200274 def add_test_case_line(self, function, argument):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200275 """Parse a test case data line, looking for algorithm metadata tests."""
Gilles Peskine8c8694c2019-11-21 19:22:45 +0100276 sets = []
Gilles Peskine24827022018-09-25 18:49:23 +0200277 if function.endswith('_algorithm'):
Gilles Peskine8c8694c2019-11-21 19:22:45 +0100278 sets.append(self.algorithms)
Gilles Peskine79616682019-11-21 20:08:10 +0100279 if function == 'key_agreement_algorithm' and \
280 argument.startswith('PSA_ALG_KEY_AGREEMENT('):
281 # We only want *raw* key agreement algorithms as such, so
282 # exclude ones that are already chained with a KDF.
283 # Keep the expression as one to test as an algorithm.
284 function = 'other_algorithm'
Gilles Peskine8fa13482019-11-25 17:10:12 +0100285 sets += self.table_by_test_function[function]
Gilles Peskine2bcfc712019-11-21 19:49:26 +0100286 if self.accept_test_case_line(function, argument):
287 for s in sets:
288 s.add(argument)
Gilles Peskine24827022018-09-25 18:49:23 +0200289
290 # Regex matching a *.data line containing a test function call and
291 # its arguments. The actual definition is partly positional, but this
292 # regex is good enough in practice.
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200293 _test_case_line_re = re.compile(r'(?!depends_on:)(\w+):([^\n :][^:\n]*)')
Gilles Peskine24827022018-09-25 18:49:23 +0200294 def parse_test_cases(self, filename):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200295 """Parse a test case file (*.data), looking for algorithm metadata tests."""
Gilles Peskinea0a315c2018-10-19 11:27:10 +0200296 with read_file_lines(filename) as lines:
297 for line in lines:
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200298 m = re.match(self._test_case_line_re, line)
Gilles Peskine24827022018-09-25 18:49:23 +0200299 if m:
300 self.add_test_case_line(m.group(1), m.group(2))
301
Gilles Peskine84a45812019-11-21 19:50:33 +0100302def gather_inputs(headers, test_suites, inputs_class=Inputs):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200303 """Read the list of inputs to test psa_constant_names with."""
Gilles Peskine84a45812019-11-21 19:50:33 +0100304 inputs = inputs_class()
Gilles Peskine24827022018-09-25 18:49:23 +0200305 for header in headers:
306 inputs.parse_header(header)
307 for test_cases in test_suites:
308 inputs.parse_test_cases(test_cases)
309 inputs.gather_arguments()
310 return inputs
311
Gilles Peskineb86b6d32019-11-21 17:26:10 +0100312def run_c(type_word, expressions, include_path=None, keep_c=False):
Gilles Peskine2991b5f2021-01-19 21:19:02 +0100313 """Generate and run a program to print out numerical values of C expressions."""
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200314 if type_word == 'status':
Gilles Peskinec4cd2ad2019-02-13 18:42:53 +0100315 cast_to = 'long'
316 printf_format = '%ld'
317 else:
318 cast_to = 'unsigned long'
319 printf_format = '0x%08lx'
Gilles Peskine2adebc82020-12-11 00:30:53 +0100320 return c_build_helper.get_c_expression_values(
Gilles Peskinefc622112020-12-11 00:27:14 +0100321 cast_to, printf_format,
322 expressions,
323 caller='test_psa_constant_names.py for {} values'.format(type_word),
324 file_label=type_word,
325 header='#include <psa/crypto.h>',
326 include_path=include_path,
327 keep_c=keep_c
328 )
Gilles Peskine24827022018-09-25 18:49:23 +0200329
Gilles Peskine42a0a0a2019-05-27 18:29:47 +0200330NORMALIZE_STRIP_RE = re.compile(r'\s+')
Gilles Peskine24827022018-09-25 18:49:23 +0200331def normalize(expr):
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200332 """Normalize the C expression so as not to care about trivial differences.
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100333
Gilles Peskinea3b93ff2019-06-03 11:23:56 +0200334 Currently "trivial differences" means whitespace.
335 """
Gilles Peskine5a6dc892019-11-21 16:48:07 +0100336 return re.sub(NORMALIZE_STRIP_RE, '', expr)
Gilles Peskine24827022018-09-25 18:49:23 +0200337
Gilles Peskineb86b6d32019-11-21 17:26:10 +0100338def collect_values(inputs, type_word, include_path=None, keep_c=False):
Gilles Peskinec2317112019-11-21 17:17:39 +0100339 """Generate expressions using known macro names and calculate their values.
340
341 Return a list of pairs of (expr, value) where expr is an expression and
342 value is a string representation of its integer value.
343 """
344 names = inputs.get_names(type_word)
345 expressions = sorted(inputs.generate_expressions(names))
Gilles Peskineb86b6d32019-11-21 17:26:10 +0100346 values = run_c(type_word, expressions,
347 include_path=include_path, keep_c=keep_c)
Gilles Peskinec2317112019-11-21 17:17:39 +0100348 return expressions, values
349
Gilles Peskine24609332019-11-21 17:44:21 +0100350class Tests:
351 """An object representing tests and their results."""
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100352
Gilles Peskinea5000f12019-11-21 17:51:11 +0100353 Error = namedtuple('Error',
354 ['type', 'expression', 'value', 'output'])
355
Gilles Peskine24609332019-11-21 17:44:21 +0100356 def __init__(self, options):
357 self.options = options
358 self.count = 0
359 self.errors = []
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100360
Gilles Peskine24609332019-11-21 17:44:21 +0100361 def run_one(self, inputs, type_word):
362 """Test psa_constant_names for the specified type.
Gilles Peskine24827022018-09-25 18:49:23 +0200363
Gilles Peskine24609332019-11-21 17:44:21 +0100364 Run the program on the names for this type.
365 Use the inputs to figure out what arguments to pass to macros that
366 take arguments.
367 """
368 expressions, values = collect_values(inputs, type_word,
369 include_path=self.options.include,
370 keep_c=self.options.keep_c)
371 output = subprocess.check_output([self.options.program, type_word] +
372 values)
373 outputs = output.decode('ascii').strip().split('\n')
374 self.count += len(expressions)
375 for expr, value, output in zip(expressions, values, outputs):
Gilles Peskine32558482019-12-03 19:03:35 +0100376 if self.options.show:
377 sys.stdout.write('{} {}\t{}\n'.format(type_word, value, output))
Gilles Peskine24609332019-11-21 17:44:21 +0100378 if normalize(expr) != normalize(output):
Gilles Peskinea5000f12019-11-21 17:51:11 +0100379 self.errors.append(self.Error(type=type_word,
380 expression=expr,
381 value=value,
382 output=output))
Gilles Peskine24827022018-09-25 18:49:23 +0200383
Gilles Peskine24609332019-11-21 17:44:21 +0100384 def run_all(self, inputs):
385 """Run psa_constant_names on all the gathered inputs."""
386 for type_word in ['status', 'algorithm', 'ecc_curve', 'dh_group',
387 'key_type', 'key_usage']:
388 self.run_one(inputs, type_word)
Gilles Peskine4408dfd2019-11-21 17:16:21 +0100389
Gilles Peskine24609332019-11-21 17:44:21 +0100390 def report(self, out):
391 """Describe each case where the output is not as expected.
392
393 Write the errors to ``out``.
394 Also write a total.
395 """
Gilles Peskinea5000f12019-11-21 17:51:11 +0100396 for error in self.errors:
Gilles Peskine24609332019-11-21 17:44:21 +0100397 out.write('For {} "{}", got "{}" (value: {})\n'
Gilles Peskinea5000f12019-11-21 17:51:11 +0100398 .format(error.type, error.expression,
399 error.output, error.value))
Gilles Peskine24609332019-11-21 17:44:21 +0100400 out.write('{} test cases'.format(self.count))
401 if self.errors:
402 out.write(', {} FAIL\n'.format(len(self.errors)))
403 else:
404 out.write(' PASS\n')
Gilles Peskine24827022018-09-25 18:49:23 +0200405
Gilles Peskine69f93b52019-11-21 16:49:50 +0100406HEADERS = ['psa/crypto.h', 'psa/crypto_extra.h', 'psa/crypto_values.h']
407TEST_SUITES = ['tests/suites/test_suite_psa_crypto_metadata.data']
408
Gilles Peskine54f54452019-05-27 18:31:59 +0200409def main():
Gilles Peskine24827022018-09-25 18:49:23 +0200410 parser = argparse.ArgumentParser(description=globals()['__doc__'])
411 parser.add_argument('--include', '-I',
412 action='append', default=['include'],
413 help='Directory for header files')
Gilles Peskinecf9c18e2018-10-19 11:28:42 +0200414 parser.add_argument('--keep-c',
415 action='store_true', dest='keep_c', default=False,
416 help='Keep the intermediate C file')
417 parser.add_argument('--no-keep-c',
418 action='store_false', dest='keep_c',
419 help='Don\'t keep the intermediate C file (default)')
Gilles Peskine8f5a5012019-11-21 16:49:10 +0100420 parser.add_argument('--program',
421 default='programs/psa/psa_constant_names',
422 help='Program to test')
Gilles Peskine32558482019-12-03 19:03:35 +0100423 parser.add_argument('--show',
424 action='store_true',
425 help='Keep the intermediate C file')
426 parser.add_argument('--no-show',
427 action='store_false', dest='show',
428 help='Don\'t show tested values (default)')
Gilles Peskine24827022018-09-25 18:49:23 +0200429 options = parser.parse_args()
Gilles Peskine69f93b52019-11-21 16:49:50 +0100430 headers = [os.path.join(options.include[0], h) for h in HEADERS]
431 inputs = gather_inputs(headers, TEST_SUITES)
Gilles Peskine24609332019-11-21 17:44:21 +0100432 tests = Tests(options)
433 tests.run_all(inputs)
434 tests.report(sys.stdout)
435 if tests.errors:
Gilles Peskine8b022352020-03-24 18:36:56 +0100436 sys.exit(1)
Gilles Peskine54f54452019-05-27 18:31:59 +0200437
438if __name__ == '__main__':
439 main()