blob: ece35dfb402af2f0744df72c15f38fb7d7f599f6 [file] [log] [blame]
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +01001#!/usr/bin/env python3
Azim Khanf0e42fb2017-08-02 14:47:13 +01002# Test suites code generator.
3#
Azim Khan8d686bf2018-07-04 23:29:46 +01004# Copyright (C) 2018, Arm Limited, All Rights Reserved
Azim Khanf0e42fb2017-08-02 14:47:13 +01005# SPDX-License-Identifier: Apache-2.0
6#
7# Licensed under the Apache License, Version 2.0 (the "License"); you may
8# not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
Azim Khanb31aa442018-07-03 11:57:54 +010019# This file is part of Mbed TLS (https://tls.mbed.org)
Azim Khanf0e42fb2017-08-02 14:47:13 +010020
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010021"""
Azim Khanaee05bb2018-07-02 16:01:04 +010022This script is a key part of Mbed TLS test suites framework. For
23understanding the script it is important to understand the
24framework. This doc string contains a summary of the framework
25and explains the function of this script.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +010026
Azim Khanaee05bb2018-07-02 16:01:04 +010027Mbed TLS test suites:
28=====================
29Scope:
30------
31The test suites focus on unit testing the crypto primitives and also
Azim Khanb31aa442018-07-03 11:57:54 +010032include x509 parser tests. Tests can be added to test any Mbed TLS
Azim Khanaee05bb2018-07-02 16:01:04 +010033module. However, the framework is not capable of testing SSL
34protocol, since that requires full stack execution and that is best
35tested as part of the system test.
36
37Test case definition:
38---------------------
39Tests are defined in a test_suite_<module>[.<optional sub module>].data
40file. A test definition contains:
41 test name
42 optional build macro dependencies
43 test function
44 test parameters
45
46Test dependencies are build macros that can be specified to indicate
47the build config in which the test is valid. For example if a test
48depends on a feature that is only enabled by defining a macro. Then
49that macro should be specified as a dependency of the test.
50
51Test function is the function that implements the test steps. This
52function is specified for different tests that perform same steps
53with different parameters.
54
55Test parameters are specified in string form separated by ':'.
56Parameters can be of type string, binary data specified as hex
57string and integer constants specified as integer, macro or
58as an expression. Following is an example test definition:
59
60X509 CRL Unsupported critical extension (issuingDistributionPoint)
61depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
Azim Khanb31aa442018-07-03 11:57:54 +010062mbedtls_x509_crl_parse:"data_files/crl-idp.pem":\
63 MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG
Azim Khanaee05bb2018-07-02 16:01:04 +010064
65Test functions:
66---------------
67Test functions are coded in C in test_suite_<module>.function files.
68Functions file is itself not compilable and contains special
69format patterns to specify test suite dependencies, start and end
70of functions and function dependencies. Check any existing functions
71file for example.
72
73Execution:
74----------
75Tests are executed in 3 steps:
76- Generating test_suite_<module>[.<optional sub module>].c file
77 for each corresponding .data file.
78- Building each source file into executables.
79- Running each executable and printing report.
80
81Generating C test source requires more than just the test functions.
82Following extras are required:
83- Process main()
84- Reading .data file and dispatching test cases.
85- Platform specific test case execution
86- Dependency checking
87- Integer expression evaluation
88- Test function dispatch
89
90Build dependencies and integer expressions (in the test parameters)
91are specified as strings in the .data file. Their run time value is
92not known at the generation stage. Hence, they need to be translated
93into run time evaluations. This script generates the run time checks
94for dependencies and integer expressions.
95
96Similarly, function names have to be translated into function calls.
97This script also generates code for function dispatch.
98
99The extra code mentioned here is either generated by this script
100or it comes from the input files: helpers file, platform file and
101the template file.
102
103Helper file:
104------------
105Helpers file contains common helper/utility functions and data.
106
107Platform file:
108--------------
109Platform file contains platform specific setup code and test case
110dispatch code. For example, host_test.function reads test data
111file from host's file system and dispatches tests.
112In case of on-target target_test.function tests are not dispatched
113on target. Target code is kept minimum and only test functions are
114dispatched. Test case dispatch is done on the host using tools like
115Greentea.
116
117Template file:
118---------
119Template file for example main_test.function is a template C file in
120which generated code and code from input files is substituted to
121generate a compilable C file. It also contains skeleton functions for
122dependency checks, expression evaluation and function dispatch. These
123functions are populated with checks and return codes by this script.
124
125Template file contains "replacement" fields that are formatted
126strings processed by Python str.format() method.
127
128This script:
129============
130Core function of this script is to fill the template file with
131code that is generated or read from helpers and platform files.
132
133This script replaces following fields in the template and generates
134the test source file:
135
136{test_common_helpers} <-- All common code from helpers.function
137 is substituted here.
138{functions_code} <-- Test functions are substituted here
139 from the input test_suit_xyz.function
140 file. C preprocessor checks are generated
141 for the build dependencies specified
142 in the input file. This script also
143 generates wrappers for the test
144 functions with code to expand the
145 string parameters read from the data
146 file.
147{expression_code} <-- This script enumerates the
148 expressions in the .data file and
149 generates code to handle enumerated
150 expression Ids and return the values.
151{dep_check_code} <-- This script enumerates all
152 build dependencies and generate
153 code to handle enumerated build
154 dependency Id and return status: if
155 the dependency is defined or not.
156{dispatch_code} <-- This script enumerates the functions
157 specified in the input test data file
158 and generates the initializer for the
159 function table in the template
160 file.
161{platform_code} <-- Platform specific setup and test
162 dispatch code.
163
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100164"""
165
Azim Khanf0e42fb2017-08-02 14:47:13 +0100166
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100167import io
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100168import os
169import re
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100170import sys
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100171import argparse
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100172
173
Azim Khanb31aa442018-07-03 11:57:54 +0100174BEGIN_HEADER_REGEX = r'/\*\s*BEGIN_HEADER\s*\*/'
175END_HEADER_REGEX = r'/\*\s*END_HEADER\s*\*/'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100176
Azim Khanb31aa442018-07-03 11:57:54 +0100177BEGIN_SUITE_HELPERS_REGEX = r'/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
178END_SUITE_HELPERS_REGEX = r'/\*\s*END_SUITE_HELPERS\s*\*/'
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000179
Azim Khanb31aa442018-07-03 11:57:54 +0100180BEGIN_DEP_REGEX = r'BEGIN_DEPENDENCIES'
181END_DEP_REGEX = r'END_DEPENDENCIES'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100182
Azim Khan8d686bf2018-07-04 23:29:46 +0100183BEGIN_CASE_REGEX = r'/\*\s*BEGIN_CASE\s*(?P<depends_on>.*?)\s*\*/'
Azim Khanb31aa442018-07-03 11:57:54 +0100184END_CASE_REGEX = r'/\*\s*END_CASE\s*\*/'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100185
Azim Khan8d686bf2018-07-04 23:29:46 +0100186DEPENDENCY_REGEX = r'depends_on:(?P<dependencies>.*)'
187C_IDENTIFIER_REGEX = r'!?[a-z_][a-z0-9_]*'
Azim Khanfcdf6852018-07-05 17:31:46 +0100188TEST_FUNCTION_VALIDATION_REGEX = r'\s*void\s+(?P<func_name>\w+)\s*\('
Azim Khan8d686bf2018-07-04 23:29:46 +0100189INT_CHECK_REGEX = r'int\s+.*'
190CHAR_CHECK_REGEX = r'char\s*\*\s*.*'
191DATA_T_CHECK_REGEX = r'data_t\s*\*\s*.*'
Azim Khan8d686bf2018-07-04 23:29:46 +0100192FUNCTION_ARG_LIST_END_REGEX = r'.*\)'
193EXIT_LABEL_REGEX = r'^exit:'
194
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100195
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100196class GeneratorInputError(Exception):
197 """
Azim Khane3b26af2018-06-29 02:36:57 +0100198 Exception to indicate error in the input files to this script.
199 This includes missing patterns, test function names and other
200 parsing errors.
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100201 """
202 pass
203
204
Azim Khanb31aa442018-07-03 11:57:54 +0100205class FileWrapper(io.FileIO, object):
Azim Khan4b543232017-06-30 09:35:21 +0100206 """
Azim Khane3b26af2018-06-29 02:36:57 +0100207 This class extends built-in io.FileIO class with attribute line_no,
208 that indicates line number for the line that is read.
Azim Khan4b543232017-06-30 09:35:21 +0100209 """
210
211 def __init__(self, file_name):
212 """
Azim Khane3b26af2018-06-29 02:36:57 +0100213 Instantiate the base class and initialize the line number to 0.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100214
Azim Khanf0e42fb2017-08-02 14:47:13 +0100215 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +0100216 """
217 super(FileWrapper, self).__init__(file_name, 'r')
Azim Khanb31aa442018-07-03 11:57:54 +0100218 self._line_no = 0
Azim Khan4b543232017-06-30 09:35:21 +0100219
Azim Khanb31aa442018-07-03 11:57:54 +0100220 def next(self):
Azim Khan4b543232017-06-30 09:35:21 +0100221 """
Azim Khane3b26af2018-06-29 02:36:57 +0100222 Python 2 iterator method. This method overrides base class's
223 next method and extends the next method to count the line
224 numbers as each line is read.
225
226 It works for both Python 2 and Python 3 by checking iterator
227 method name in the base iterator object.
228
Azim Khanf0e42fb2017-08-02 14:47:13 +0100229 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +0100230 """
Gilles Peskine667f7f82018-06-18 17:51:56 +0200231 parent = super(FileWrapper, self)
232 if hasattr(parent, '__next__'):
Azim Khanb31aa442018-07-03 11:57:54 +0100233 line = parent.__next__() # Python 3
Gilles Peskine667f7f82018-06-18 17:51:56 +0200234 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100235 line = parent.next() # Python 2
236 if line is not None:
237 self._line_no += 1
Azim Khan936ea932018-06-28 16:47:12 +0100238 # Convert byte array to string with correct encoding and
239 # strip any whitespaces added in the decoding process.
Azim Khan8d686bf2018-07-04 23:29:46 +0100240 return line.decode(sys.getdefaultencoding()).rstrip() + '\n'
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100241 return None
Azim Khane3b26af2018-06-29 02:36:57 +0100242
243 # Python 3 iterator method
Azim Khanb31aa442018-07-03 11:57:54 +0100244 __next__ = next
245
246 def get_line_no(self):
247 """
248 Gives current line number.
249 """
250 return self._line_no
251
252 line_no = property(get_line_no)
Azim Khan4b543232017-06-30 09:35:21 +0100253
254
255def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100256 """
Azim Khanb31aa442018-07-03 11:57:54 +0100257 Split NOT character '!' from dependency. Used by gen_dependencies()
Azim Khanf0e42fb2017-08-02 14:47:13 +0100258
259 :param dep: Dependency list
Azim Khane3b26af2018-06-29 02:36:57 +0100260 :return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
261 MACRO.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100262 """
Azim Khan4b543232017-06-30 09:35:21 +0100263 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
264
265
Azim Khanb31aa442018-07-03 11:57:54 +0100266def gen_dependencies(dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100267 """
Azim Khane3b26af2018-06-29 02:36:57 +0100268 Test suite data and functions specifies compile time dependencies.
269 This function generates C preprocessor code from the input
270 dependency list. Caller uses the generated preprocessor code to
271 wrap dependent code.
272 A dependency in the input list can have a leading '!' character
273 to negate a condition. '!' is separated from the dependency using
274 function split_dep() and proper preprocessor check is generated
275 accordingly.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100276
Azim Khanb31aa442018-07-03 11:57:54 +0100277 :param dependencies: List of dependencies.
Azim Khan040b6a22018-06-28 16:49:13 +0100278 :return: if defined and endif code with macro annotations for
279 readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100280 """
Azim Khanb31aa442018-07-03 11:57:54 +0100281 dep_start = ''.join(['#if %sdefined(%s)\n' % (x, y) for x, y in
282 map(split_dep, dependencies)])
283 dep_end = ''.join(['#endif /* %s */\n' %
284 x for x in reversed(dependencies)])
Azim Khan4b543232017-06-30 09:35:21 +0100285
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100286 return dep_start, dep_end
287
288
Azim Khanb31aa442018-07-03 11:57:54 +0100289def gen_dependencies_one_line(dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100290 """
Azim Khanb31aa442018-07-03 11:57:54 +0100291 Similar to gen_dependencies() but generates dependency checks in one line.
Azim Khane3b26af2018-06-29 02:36:57 +0100292 Useful for generating code with #else block.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100293
Azim Khanb31aa442018-07-03 11:57:54 +0100294 :param dependencies: List of dependencies.
295 :return: Preprocessor check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100296 """
Azim Khanb31aa442018-07-03 11:57:54 +0100297 defines = '#if ' if dependencies else ''
298 defines += ' && '.join(['%sdefined(%s)' % (x, y) for x, y in map(
299 split_dep, dependencies)])
Azim Khan4b543232017-06-30 09:35:21 +0100300 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100301
302
Azim Khanb31aa442018-07-03 11:57:54 +0100303def gen_function_wrapper(name, local_vars, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100304 """
Azim Khan040b6a22018-06-28 16:49:13 +0100305 Creates test function wrapper code. A wrapper has the code to
306 unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100307
Azim Khanf0e42fb2017-08-02 14:47:13 +0100308 :param name: Test function name
Azim Khanb31aa442018-07-03 11:57:54 +0100309 :param local_vars: Local variables declaration code
Azim Khan040b6a22018-06-28 16:49:13 +0100310 :param args_dispatch: List of dispatch arguments.
311 Ex: ['(char *)params[0]', '*((int *)params[1])']
Azim Khanf0e42fb2017-08-02 14:47:13 +0100312 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100313 """
314 # Then create the wrapper
315 wrapper = '''
316void {name}_wrapper( void ** params )
317{{
Gilles Peskine77761412018-06-18 17:51:40 +0200318{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100319 {name}( {args} );
320}}
Gilles Peskine77761412018-06-18 17:51:40 +0200321'''.format(name=name,
Mohammad Azim Khanc3521df2018-06-26 14:06:52 +0100322 unused_params='' if args_dispatch else ' (void)params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100323 args=', '.join(args_dispatch),
Azim Khanb31aa442018-07-03 11:57:54 +0100324 locals=local_vars)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100325 return wrapper
326
327
Azim Khanb31aa442018-07-03 11:57:54 +0100328def gen_dispatch(name, dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100329 """
Azim Khane3b26af2018-06-29 02:36:57 +0100330 Test suite code template main_test.function defines a C function
331 array to contain test case functions. This function generates an
332 initializer entry for a function in that array. The entry is
333 composed of a compile time check for the test function
334 dependencies. At compile time the test function is assigned when
335 dependencies are met, else NULL is assigned.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100336
Azim Khanf0e42fb2017-08-02 14:47:13 +0100337 :param name: Test function name
Azim Khanb31aa442018-07-03 11:57:54 +0100338 :param dependencies: List of dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100339 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100340 """
Azim Khanb31aa442018-07-03 11:57:54 +0100341 if dependencies:
342 preprocessor_check = gen_dependencies_one_line(dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100343 dispatch_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100344{preprocessor_check}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100345 {name}_wrapper,
346#else
347 NULL,
348#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100349'''.format(preprocessor_check=preprocessor_check, name=name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100350 else:
351 dispatch_code = '''
352 {name}_wrapper,
353'''.format(name=name)
354
355 return dispatch_code
356
357
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000358def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100359 """
Azim Khane3b26af2018-06-29 02:36:57 +0100360 Matches pattern end_regex to the lines read from the file object.
361 Returns the lines read until end pattern is matched.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100362
Azim Khan8d686bf2018-07-04 23:29:46 +0100363 :param funcs_f: file object for .function file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000364 :param end_regex: Pattern to stop parsing
Azim Khane3b26af2018-06-29 02:36:57 +0100365 :return: Lines read before the end pattern
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100366 """
Azim Khan4b543232017-06-30 09:35:21 +0100367 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100368 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000369 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100370 break
371 headers += line
372 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100373 raise GeneratorInputError("file: %s - end pattern [%s] not found!" %
Azim Khanb31aa442018-07-03 11:57:54 +0100374 (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100375
Azim Khan4b543232017-06-30 09:35:21 +0100376 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100377
378
Azim Khan8d686bf2018-07-04 23:29:46 +0100379def validate_dependency(dependency):
380 """
381 Validates a C macro and raises GeneratorInputError on invalid input.
382 :param dependency: Input macro dependency
383 :return: input dependency stripped of leading & trailing white spaces.
384 """
385 dependency = dependency.strip()
386 if not re.match(C_IDENTIFIER_REGEX, dependency, re.I):
387 raise GeneratorInputError('Invalid dependency %s' % dependency)
388 return dependency
389
390
391def parse_dependencies(inp_str):
392 """
393 Parses dependencies out of inp_str, validates them and returns a
394 list of macros.
395
396 :param inp_str: Input string with macros delimited by ':'.
397 :return: list of dependencies
398 """
399 dependencies = [dep for dep in map(validate_dependency,
400 inp_str.split(':'))]
401 return dependencies
402
403
Azim Khanb31aa442018-07-03 11:57:54 +0100404def parse_suite_dependencies(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100405 """
Azim Khane3b26af2018-06-29 02:36:57 +0100406 Parses test suite dependencies specified at the top of a
407 .function file, that starts with pattern BEGIN_DEPENDENCIES
408 and end with END_DEPENDENCIES. Dependencies are specified
409 after pattern 'depends_on:' and are delimited by ':'.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100410
Azim Khan8d686bf2018-07-04 23:29:46 +0100411 :param funcs_f: file object for .function file
Azim Khanf0e42fb2017-08-02 14:47:13 +0100412 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100413 """
Azim Khanb31aa442018-07-03 11:57:54 +0100414 dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100415 for line in funcs_f:
Azim Khan8d686bf2018-07-04 23:29:46 +0100416 match = re.search(DEPENDENCY_REGEX, line.strip())
Azim Khanb31aa442018-07-03 11:57:54 +0100417 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100418 try:
419 dependencies = parse_dependencies(match.group('dependencies'))
420 except GeneratorInputError as error:
421 raise GeneratorInputError(
422 str(error) + " - %s:%d" % (funcs_f.name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100423 if re.search(END_DEP_REGEX, line):
424 break
425 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100426 raise GeneratorInputError("file: %s - end dependency pattern [%s]"
Azim Khanb31aa442018-07-03 11:57:54 +0100427 " not found!" % (funcs_f.name,
428 END_DEP_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100429
Azim Khanb31aa442018-07-03 11:57:54 +0100430 return dependencies
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100431
432
Azim Khanb31aa442018-07-03 11:57:54 +0100433def parse_function_dependencies(line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100434 """
Azim Khane3b26af2018-06-29 02:36:57 +0100435 Parses function dependencies, that are in the same line as
436 comment BEGIN_CASE. Dependencies are specified after pattern
437 'depends_on:' and are delimited by ':'.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100438
Azim Khan8d686bf2018-07-04 23:29:46 +0100439 :param line: Line from .function file that has dependencies.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100440 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100441 """
Azim Khanb31aa442018-07-03 11:57:54 +0100442 dependencies = []
443 match = re.search(BEGIN_CASE_REGEX, line)
Azim Khan8d686bf2018-07-04 23:29:46 +0100444 dep_str = match.group('depends_on')
Azim Khanb31aa442018-07-03 11:57:54 +0100445 if dep_str:
Azim Khan8d686bf2018-07-04 23:29:46 +0100446 match = re.search(DEPENDENCY_REGEX, dep_str)
Azim Khanb31aa442018-07-03 11:57:54 +0100447 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100448 dependencies += parse_dependencies(match.group('dependencies'))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100449
Azim Khan8d686bf2018-07-04 23:29:46 +0100450 return dependencies
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100451
Azim Khan4084ec72018-07-05 14:20:08 +0100452
Azim Khanfcdf6852018-07-05 17:31:46 +0100453def parse_function_arguments(line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100454 """
Azim Khane3b26af2018-06-29 02:36:57 +0100455 Parses test function signature for validation and generates
456 a dispatch wrapper function that translates input test vectors
457 read from the data file into test function arguments.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100458
Azim Khan8d686bf2018-07-04 23:29:46 +0100459 :param line: Line from .function file that has a function
Azim Khan040b6a22018-06-28 16:49:13 +0100460 signature.
Azim Khanfcdf6852018-07-05 17:31:46 +0100461 :return: argument list, local variables for
Azim Khan040b6a22018-06-28 16:49:13 +0100462 wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100463 """
464 args = []
Azim Khanb31aa442018-07-03 11:57:54 +0100465 local_vars = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100466 args_dispatch = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100467 arg_idx = 0
Azim Khanfcdf6852018-07-05 17:31:46 +0100468 # Remove characters before arguments
469 line = line[line.find('(') + 1:]
Azim Khan8d686bf2018-07-04 23:29:46 +0100470 # Process arguments, ex: <type> arg1, <type> arg2 )
471 # This script assumes that the argument list is terminated by ')'
472 # i.e. the test functions will not have a function pointer
473 # argument.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100474 for arg in line[:line.find(')')].split(','):
475 arg = arg.strip()
476 if arg == '':
477 continue
Azim Khan8d686bf2018-07-04 23:29:46 +0100478 if re.search(INT_CHECK_REGEX, arg.strip()):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100479 args.append('int')
480 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
Azim Khan8d686bf2018-07-04 23:29:46 +0100481 elif re.search(CHAR_CHECK_REGEX, arg.strip()):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100482 args.append('char*')
483 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan8d686bf2018-07-04 23:29:46 +0100484 elif re.search(DATA_T_CHECK_REGEX, arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100485 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100486 # create a structure
Azim Khan040b6a22018-06-28 16:49:13 +0100487 pointer_initializer = '(uint8_t *) params[%d]' % arg_idx
488 len_initializer = '*( (uint32_t *) params[%d] )' % (arg_idx+1)
Azim Khanb31aa442018-07-03 11:57:54 +0100489 local_vars += """ data_t data%d = {%s, %s};
Azim Khan040b6a22018-06-28 16:49:13 +0100490""" % (arg_idx, pointer_initializer, len_initializer)
Azim Khan2397bba2017-06-09 04:35:03 +0100491
Azim Khan5fcca462018-06-29 11:05:32 +0100492 args_dispatch.append('&data%d' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100493 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100494 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100495 raise ValueError("Test function arguments can only be 'int', "
Azim Khan5fcca462018-06-29 11:05:32 +0100496 "'char *' or 'data_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100497 arg_idx += 1
498
Azim Khanfcdf6852018-07-05 17:31:46 +0100499 return args, local_vars, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100500
501
Azim Khanb31aa442018-07-03 11:57:54 +0100502def parse_function_code(funcs_f, dependencies, suite_dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100503 """
Azim Khan040b6a22018-06-28 16:49:13 +0100504 Parses out a function from function file object and generates
505 function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100506
Azim Khanf0e42fb2017-08-02 14:47:13 +0100507 :param funcs_f: file object of the functions file.
Azim Khanb31aa442018-07-03 11:57:54 +0100508 :param dependencies: List of dependencies
509 :param suite_dependencies: List of test suite dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100510 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100511 """
Azim Khanfcdf6852018-07-05 17:31:46 +0100512 line_directive = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
513 code = ''
Azim Khan8d686bf2018-07-04 23:29:46 +0100514 has_exit_label = False
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100515 for line in funcs_f:
Azim Khanfcdf6852018-07-05 17:31:46 +0100516 # Check function signature. Function signature may be split
517 # across multiple lines. Here we try to find the start of
518 # arguments list, then remove '\n's and apply the regex to
519 # detect function start.
520 up_to_arg_list_start = code + line[:line.find('(') + 1]
521 match = re.match(TEST_FUNCTION_VALIDATION_REGEX,
522 up_to_arg_list_start.replace('\n', ' '), re.I)
Azim Khanb31aa442018-07-03 11:57:54 +0100523 if match:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100524 # check if we have full signature i.e. split in more lines
Azim Khanfcdf6852018-07-05 17:31:46 +0100525 name = match.group('func_name')
Azim Khan8d686bf2018-07-04 23:29:46 +0100526 if not re.match(FUNCTION_ARG_LIST_END_REGEX, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100527 for lin in funcs_f:
528 line += lin
Azim Khan8d686bf2018-07-04 23:29:46 +0100529 if re.search(FUNCTION_ARG_LIST_END_REGEX, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100530 break
Azim Khanfcdf6852018-07-05 17:31:46 +0100531 args, local_vars, args_dispatch = parse_function_arguments(
Azim Khanb31aa442018-07-03 11:57:54 +0100532 line)
Azim Khan8d686bf2018-07-04 23:29:46 +0100533 code += line
Azim Khanfcdf6852018-07-05 17:31:46 +0100534 break
535 code += line
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100536 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100537 raise GeneratorInputError("file: %s - Test functions not found!" %
Azim Khanb31aa442018-07-03 11:57:54 +0100538 funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100539
Azim Khanfcdf6852018-07-05 17:31:46 +0100540 # Prefix test function name with 'test_'
541 code = code.replace(name, 'test_' + name, 1)
542 name = 'test_' + name
543
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100544 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100545 if re.search(END_CASE_REGEX, line):
546 break
Azim Khan8d686bf2018-07-04 23:29:46 +0100547 if not has_exit_label:
548 has_exit_label = \
549 re.search(EXIT_LABEL_REGEX, line.strip()) is not None
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100550 code += line
551 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100552 raise GeneratorInputError("file: %s - end case pattern [%s] not "
Azim Khanb31aa442018-07-03 11:57:54 +0100553 "found!" % (funcs_f.name, END_CASE_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100554
555 # Add exit label if not present
556 if code.find('exit:') == -1:
Azim Khanb31aa442018-07-03 11:57:54 +0100557 split_code = code.rsplit('}', 1)
558 if len(split_code) == 2:
Azim Khan4b543232017-06-30 09:35:21 +0100559 code = """exit:
Azim Khan8d686bf2018-07-04 23:29:46 +0100560 ;
Azim Khanb31aa442018-07-03 11:57:54 +0100561}""".join(split_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100562
Azim Khanfcdf6852018-07-05 17:31:46 +0100563 code = line_directive + code + gen_function_wrapper(name, local_vars,
564 args_dispatch)
Azim Khanb31aa442018-07-03 11:57:54 +0100565 preprocessor_check_start, preprocessor_check_end = \
566 gen_dependencies(dependencies)
567 dispatch_code = gen_dispatch(name, suite_dependencies + dependencies)
568 return (name, args, preprocessor_check_start + code +
569 preprocessor_check_end, dispatch_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100570
571
572def parse_functions(funcs_f):
573 """
Azim Khane3b26af2018-06-29 02:36:57 +0100574 Parses a test_suite_xxx.function file and returns information
575 for generating a C source file for the test suite.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100576
Azim Khanf0e42fb2017-08-02 14:47:13 +0100577 :param funcs_f: file object of the functions file.
Azim Khan040b6a22018-06-28 16:49:13 +0100578 :return: List of test suite dependencies, test function dispatch
579 code, function code and a dict with function identifiers
580 and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100581 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000582 suite_helpers = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100583 suite_dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100584 suite_functions = ''
585 func_info = {}
586 function_idx = 0
587 dispatch_code = ''
588 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100589 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000590 headers = parse_until_pattern(funcs_f, END_HEADER_REGEX)
Azim Khanb31aa442018-07-03 11:57:54 +0100591 suite_helpers += headers
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000592 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
593 helpers = parse_until_pattern(funcs_f, END_SUITE_HELPERS_REGEX)
594 suite_helpers += helpers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100595 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khanb31aa442018-07-03 11:57:54 +0100596 suite_dependencies += parse_suite_dependencies(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100597 elif re.search(BEGIN_CASE_REGEX, line):
Azim Khan8d686bf2018-07-04 23:29:46 +0100598 try:
599 dependencies = parse_function_dependencies(line)
600 except GeneratorInputError as error:
601 raise GeneratorInputError(
602 "%s:%d: %s" % (funcs_f.name, funcs_f.line_no,
603 str(error)))
Azim Khan040b6a22018-06-28 16:49:13 +0100604 func_name, args, func_code, func_dispatch =\
Azim Khanb31aa442018-07-03 11:57:54 +0100605 parse_function_code(funcs_f, dependencies, suite_dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100606 suite_functions += func_code
607 # Generate dispatch code and enumeration info
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100608 if func_name in func_info:
609 raise GeneratorInputError(
Azim Khanb31aa442018-07-03 11:57:54 +0100610 "file: %s - function %s re-declared at line %d" %
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100611 (funcs_f.name, func_name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100612 func_info[func_name] = (function_idx, args)
613 dispatch_code += '/* Function Id: %d */\n' % function_idx
614 dispatch_code += func_dispatch
615 function_idx += 1
616
Azim Khanb31aa442018-07-03 11:57:54 +0100617 func_code = (suite_helpers +
618 suite_functions).join(gen_dependencies(suite_dependencies))
619 return suite_dependencies, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100620
621
Azim Khanb31aa442018-07-03 11:57:54 +0100622def escaped_split(inp_str, split_char):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100623 """
Azim Khanb31aa442018-07-03 11:57:54 +0100624 Split inp_str on character split_char but ignore if escaped.
Azim Khan040b6a22018-06-28 16:49:13 +0100625 Since, return value is used to write back to the intermediate
626 data file, any escape characters in the input are retained in the
627 output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100628
Azim Khanb31aa442018-07-03 11:57:54 +0100629 :param inp_str: String to split
Azim Khan8d686bf2018-07-04 23:29:46 +0100630 :param split_char: Split character
Azim Khanf0e42fb2017-08-02 14:47:13 +0100631 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100632 """
Azim Khanb31aa442018-07-03 11:57:54 +0100633 if len(split_char) > 1:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100634 raise ValueError('Expected split character. Found string!')
Azim Khan63028132018-07-05 17:53:11 +0100635 out = re.sub(r'(\\.)|' + split_char,
636 lambda m: m.group(1) or '\n', inp_str,
637 len(inp_str)).split('\n')
638 out = filter(lambda x: x or False, out)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100639 return out
640
641
Azim Khanb31aa442018-07-03 11:57:54 +0100642def parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100643 """
Azim Khane3b26af2018-06-29 02:36:57 +0100644 Parses .data file for each test case name, test function name,
645 test dependencies and test arguments. This information is
646 correlated with the test functions file for generating an
647 intermediate data file replacing the strings for test function
648 names, dependencies and integer constant expressions with
649 identifiers. Mainly for optimising space for on-target
650 execution.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100651
Azim Khanf0e42fb2017-08-02 14:47:13 +0100652 :param data_f: file object of the data file.
Azim Khan040b6a22018-06-28 16:49:13 +0100653 :return: Generator that yields test name, function name,
654 dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100655 """
Azim Khanb31aa442018-07-03 11:57:54 +0100656 __state_read_name = 0
657 __state_read_args = 1
658 state = __state_read_name
659 dependencies = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100660 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100661 for line in data_f:
662 line = line.strip()
Azim Khan8d686bf2018-07-04 23:29:46 +0100663 # Skip comments
664 if line.startswith('#'):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100665 continue
666
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100667 # Blank line indicates end of test
Azim Khanb31aa442018-07-03 11:57:54 +0100668 if not line:
669 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100670 raise GeneratorInputError("[%s:%d] Newline before arguments. "
671 "Test function and arguments "
672 "missing for %s" %
673 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100674 continue
675
Azim Khanb31aa442018-07-03 11:57:54 +0100676 if state == __state_read_name:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100677 # Read test name
678 name = line
Azim Khanb31aa442018-07-03 11:57:54 +0100679 state = __state_read_args
680 elif state == __state_read_args:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100681 # Check dependencies
Azim Khan8d686bf2018-07-04 23:29:46 +0100682 match = re.search(DEPENDENCY_REGEX, line)
Azim Khanb31aa442018-07-03 11:57:54 +0100683 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100684 try:
685 dependencies = parse_dependencies(
686 match.group('dependencies'))
687 except GeneratorInputError as error:
688 raise GeneratorInputError(
689 str(error) + " - %s:%d" %
690 (data_f.name, data_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100691 else:
692 # Read test vectors
693 parts = escaped_split(line, ':')
Azim Khanb31aa442018-07-03 11:57:54 +0100694 test_function = parts[0]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100695 args = parts[1:]
Azim Khanb31aa442018-07-03 11:57:54 +0100696 yield name, test_function, dependencies, args
697 dependencies = []
698 state = __state_read_name
699 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100700 raise GeneratorInputError("[%s:%d] Newline before arguments. "
701 "Test function and arguments missing for "
702 "%s" % (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100703
704
705def gen_dep_check(dep_id, dep):
706 """
Azim Khane3b26af2018-06-29 02:36:57 +0100707 Generate code for checking dependency with the associated
708 identifier.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100709
Azim Khanf0e42fb2017-08-02 14:47:13 +0100710 :param dep_id: Dependency identifier
711 :param dep: Dependency macro
712 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100713 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100714 if dep_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100715 raise GeneratorInputError("Dependency Id should be a positive "
716 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100717 _not, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
718 if not dep:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100719 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100720 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100721 case {id}:
722 {{
Azim Khanb31aa442018-07-03 11:57:54 +0100723#if {_not}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100724 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100725#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100726 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100727#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100728 }}
Azim Khanb31aa442018-07-03 11:57:54 +0100729 break;'''.format(_not=_not, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100730 return dep_check
731
732
733def gen_expression_check(exp_id, exp):
734 """
Azim Khane3b26af2018-06-29 02:36:57 +0100735 Generates code for evaluating an integer expression using
736 associated expression Id.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100737
Azim Khanf0e42fb2017-08-02 14:47:13 +0100738 :param exp_id: Expression Identifier
739 :param exp: Expression/Macro
740 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100741 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100742 if exp_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100743 raise GeneratorInputError("Expression Id should be a positive "
744 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100745 if not exp:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100746 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100747 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100748 case {exp_id}:
749 {{
750 *out_value = {expression};
751 }}
752 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100753 return exp_code
754
755
Azim Khanb31aa442018-07-03 11:57:54 +0100756def write_dependencies(out_data_f, test_dependencies, unique_dependencies):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100757 """
Azim Khane3b26af2018-06-29 02:36:57 +0100758 Write dependencies to intermediate test data file, replacing
759 the string form with identifiers. Also, generates dependency
760 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100761
Azim Khanf0e42fb2017-08-02 14:47:13 +0100762 :param out_data_f: Output intermediate data file
Azim Khanb31aa442018-07-03 11:57:54 +0100763 :param test_dependencies: Dependencies
764 :param unique_dependencies: Mutable list to track unique dependencies
Azim Khan040b6a22018-06-28 16:49:13 +0100765 that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100766 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100767 """
Azim Khan599cd242017-07-06 17:34:27 +0100768 dep_check_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100769 if test_dependencies:
Azim Khan599cd242017-07-06 17:34:27 +0100770 out_data_f.write('depends_on')
Azim Khanb31aa442018-07-03 11:57:54 +0100771 for dep in test_dependencies:
772 if dep not in unique_dependencies:
773 unique_dependencies.append(dep)
774 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100775 dep_check_code += gen_dep_check(dep_id, dep)
776 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100777 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100778 out_data_f.write(':' + str(dep_id))
779 out_data_f.write('\n')
780 return dep_check_code
781
782
783def write_parameters(out_data_f, test_args, func_args, unique_expressions):
784 """
Azim Khane3b26af2018-06-29 02:36:57 +0100785 Writes test parameters to the intermediate data file, replacing
786 the string form with identifiers. Also, generates expression
787 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100788
Azim Khanf0e42fb2017-08-02 14:47:13 +0100789 :param out_data_f: Output intermediate data file
790 :param test_args: Test parameters
791 :param func_args: Function arguments
Azim Khan040b6a22018-06-28 16:49:13 +0100792 :param unique_expressions: Mutable list to track unique
793 expressions that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100794 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100795 """
796 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100797 for i, _ in enumerate(test_args):
Azim Khan599cd242017-07-06 17:34:27 +0100798 typ = func_args[i]
799 val = test_args[i]
800
Azim Khan040b6a22018-06-28 16:49:13 +0100801 # check if val is a non literal int val (i.e. an expression)
Azim Khan8d686bf2018-07-04 23:29:46 +0100802 if typ == 'int' and not re.match(r'(\d+|0x[0-9a-f]+)$',
803 val, re.I):
Azim Khan599cd242017-07-06 17:34:27 +0100804 typ = 'exp'
805 if val not in unique_expressions:
806 unique_expressions.append(val)
Azim Khan040b6a22018-06-28 16:49:13 +0100807 # exp_id can be derived from len(). But for
808 # readability and consistency with case of existing
809 # let's use index().
Azim Khan599cd242017-07-06 17:34:27 +0100810 exp_id = unique_expressions.index(val)
811 expression_code += gen_expression_check(exp_id, val)
812 val = exp_id
813 else:
814 val = unique_expressions.index(val)
815 out_data_f.write(':' + typ + ':' + str(val))
816 out_data_f.write('\n')
817 return expression_code
818
819
Azim Khanb31aa442018-07-03 11:57:54 +0100820def gen_suite_dep_checks(suite_dependencies, dep_check_code, expression_code):
Azim Khan599cd242017-07-06 17:34:27 +0100821 """
Azim Khane3b26af2018-06-29 02:36:57 +0100822 Generates preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100823
Azim Khanb31aa442018-07-03 11:57:54 +0100824 :param suite_dependencies: Test suite dependencies read from the
Azim Khan8d686bf2018-07-04 23:29:46 +0100825 .function file.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100826 :param dep_check_code: Dependency check code
827 :param expression_code: Expression check code
Azim Khan040b6a22018-06-28 16:49:13 +0100828 :return: Dependency and expression code guarded by test suite
829 dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100830 """
Azim Khanb31aa442018-07-03 11:57:54 +0100831 if suite_dependencies:
832 preprocessor_check = gen_dependencies_one_line(suite_dependencies)
Azim Khan599cd242017-07-06 17:34:27 +0100833 dep_check_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100834{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100835{code}
Azim Khan599cd242017-07-06 17:34:27 +0100836#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100837'''.format(preprocessor_check=preprocessor_check, code=dep_check_code)
Azim Khan599cd242017-07-06 17:34:27 +0100838 expression_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100839{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100840{code}
Azim Khan599cd242017-07-06 17:34:27 +0100841#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100842'''.format(preprocessor_check=preprocessor_check, code=expression_code)
Azim Khan599cd242017-07-06 17:34:27 +0100843 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100844
845
Azim Khanb31aa442018-07-03 11:57:54 +0100846def gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100847 """
Azim Khane3b26af2018-06-29 02:36:57 +0100848 This function reads test case name, dependencies and test vectors
849 from the .data file. This information is correlated with the test
850 functions file for generating an intermediate data file replacing
851 the strings for test function names, dependencies and integer
852 constant expressions with identifiers. Mainly for optimising
853 space for on-target execution.
854 It also generates test case dependency check code and expression
855 evaluation code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100856
Azim Khanf0e42fb2017-08-02 14:47:13 +0100857 :param data_f: Data file object
Azim Khan8d686bf2018-07-04 23:29:46 +0100858 :param out_data_f: Output intermediate data file
Azim Khan040b6a22018-06-28 16:49:13 +0100859 :param func_info: Dict keyed by function and with function id
860 and arguments info
Azim Khanb31aa442018-07-03 11:57:54 +0100861 :param suite_dependencies: Test suite dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100862 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100863 """
Azim Khanb31aa442018-07-03 11:57:54 +0100864 unique_dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100865 unique_expressions = []
866 dep_check_code = ''
867 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100868 for test_name, function_name, test_dependencies, test_args in \
869 parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100870 out_data_f.write(test_name + '\n')
871
Azim Khanb31aa442018-07-03 11:57:54 +0100872 # Write dependencies
873 dep_check_code += write_dependencies(out_data_f, test_dependencies,
874 unique_dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100875
Azim Khan599cd242017-07-06 17:34:27 +0100876 # Write test function name
877 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100878 if test_function_name not in func_info:
Azim Khan040b6a22018-06-28 16:49:13 +0100879 raise GeneratorInputError("Function %s not found!" %
880 test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100881 func_id, func_args = func_info[test_function_name]
882 out_data_f.write(str(func_id))
883
884 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100885 if len(test_args) != len(func_args):
Azim Khan040b6a22018-06-28 16:49:13 +0100886 raise GeneratorInputError("Invalid number of arguments in test "
Azim Khanb31aa442018-07-03 11:57:54 +0100887 "%s. See function %s signature." %
888 (test_name, function_name))
Azim Khan040b6a22018-06-28 16:49:13 +0100889 expression_code += write_parameters(out_data_f, test_args, func_args,
890 unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100891
Azim Khan599cd242017-07-06 17:34:27 +0100892 # Write a newline as test case separator
893 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100894
Azim Khanb31aa442018-07-03 11:57:54 +0100895 dep_check_code, expression_code = gen_suite_dep_checks(
896 suite_dependencies, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100897 return dep_check_code, expression_code
898
899
Azim Khanb31aa442018-07-03 11:57:54 +0100900def add_input_info(funcs_file, data_file, template_file,
901 c_file, snippets):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100902 """
Azim Khanb31aa442018-07-03 11:57:54 +0100903 Add generator input info in snippets.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100904
Azim Khanf0e42fb2017-08-02 14:47:13 +0100905 :param funcs_file: Functions file object
906 :param data_file: Data file object
907 :param template_file: Template file object
Azim Khanf0e42fb2017-08-02 14:47:13 +0100908 :param c_file: Output C file object
Azim Khanb31aa442018-07-03 11:57:54 +0100909 :param snippets: Dictionary to contain code pieces to be
910 substituted in the template.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100911 :return:
912 """
Azim Khanb31aa442018-07-03 11:57:54 +0100913 snippets['test_file'] = c_file
914 snippets['test_main_file'] = template_file
915 snippets['test_case_file'] = funcs_file
916 snippets['test_case_data_file'] = data_file
917
918
919def read_code_from_input_files(platform_file, helpers_file,
920 out_data_file, snippets):
921 """
922 Read code from input files and create substitutions for replacement
923 strings in the template file.
924
925 :param platform_file: Platform file object
926 :param helpers_file: Helper functions file object
927 :param out_data_file: Output intermediate data file object
928 :param snippets: Dictionary to contain code pieces to be
929 substituted in the template.
930 :return:
931 """
932 # Read helpers
933 with open(helpers_file, 'r') as help_f, open(platform_file, 'r') as \
934 platform_f:
935 snippets['test_common_helper_file'] = helpers_file
936 snippets['test_common_helpers'] = help_f.read()
937 snippets['test_platform_file'] = platform_file
938 snippets['platform_code'] = platform_f.read().replace(
939 'DATA_FILE', out_data_file.replace('\\', '\\\\')) # escape '\'
940
941
942def write_test_source_file(template_file, c_file, snippets):
943 """
944 Write output source file with generated source code.
945
946 :param template_file: Template file name
947 :param c_file: Output source file
948 :param snippets: Generated and code snippets
949 :return:
950 """
951 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
952 line_no = 1
953 for line in template_f.readlines():
954 # Update line number. +1 as #line directive sets next line number
955 snippets['line_no'] = line_no + 1
956 code = line.format(**snippets)
957 c_f.write(code)
958 line_no += 1
959
960
961def parse_function_file(funcs_file, snippets):
962 """
963 Parse function file and generate function dispatch code.
964
965 :param funcs_file: Functions file name
966 :param snippets: Dictionary to contain code pieces to be
967 substituted in the template.
968 :return:
969 """
970 with FileWrapper(funcs_file) as funcs_f:
971 suite_dependencies, dispatch_code, func_code, func_info = \
972 parse_functions(funcs_f)
973 snippets['functions_code'] = func_code
974 snippets['dispatch_code'] = dispatch_code
975 return suite_dependencies, func_info
976
977
978def generate_intermediate_data_file(data_file, out_data_file,
979 suite_dependencies, func_info, snippets):
980 """
981 Generates intermediate data file from input data file and
982 information read from functions file.
983
984 :param data_file: Data file name
985 :param out_data_file: Output/Intermediate data file
986 :param suite_dependencies: List of suite dependencies.
987 :param func_info: Function info parsed from functions file.
988 :param snippets: Dictionary to contain code pieces to be
989 substituted in the template.
990 :return:
991 """
992 with FileWrapper(data_file) as data_f, \
993 open(out_data_file, 'w') as out_data_f:
994 dep_check_code, expression_code = gen_from_test_data(
995 data_f, out_data_f, func_info, suite_dependencies)
996 snippets['dep_check_code'] = dep_check_code
997 snippets['expression_code'] = expression_code
998
999
1000def generate_code(**input_info):
1001 """
1002 Generates C source code from test suite file, data file, common
1003 helpers file and platform file.
1004
1005 input_info expands to following parameters:
1006 funcs_file: Functions file object
1007 data_file: Data file object
1008 template_file: Template file object
1009 platform_file: Platform file object
1010 helpers_file: Helper functions file object
1011 suites_dir: Test suites dir
1012 c_file: Output C file object
1013 out_data_file: Output intermediate data file object
1014 :return:
1015 """
1016 funcs_file = input_info['funcs_file']
1017 data_file = input_info['data_file']
1018 template_file = input_info['template_file']
1019 platform_file = input_info['platform_file']
1020 helpers_file = input_info['helpers_file']
1021 suites_dir = input_info['suites_dir']
1022 c_file = input_info['c_file']
1023 out_data_file = input_info['out_data_file']
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001024 for name, path in [('Functions file', funcs_file),
1025 ('Data file', data_file),
1026 ('Template file', template_file),
1027 ('Platform file', platform_file),
Azim Khane3b26af2018-06-29 02:36:57 +01001028 ('Helpers code file', helpers_file),
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001029 ('Suites dir', suites_dir)]:
1030 if not os.path.exists(path):
1031 raise IOError("ERROR: %s [%s] not found!" % (name, path))
1032
Azim Khanb31aa442018-07-03 11:57:54 +01001033 snippets = {'generator_script': os.path.basename(__file__)}
1034 read_code_from_input_files(platform_file, helpers_file,
1035 out_data_file, snippets)
1036 add_input_info(funcs_file, data_file, template_file,
1037 c_file, snippets)
1038 suite_dependencies, func_info = parse_function_file(funcs_file, snippets)
1039 generate_intermediate_data_file(data_file, out_data_file,
1040 suite_dependencies, func_info, snippets)
1041 write_test_source_file(template_file, c_file, snippets)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001042
1043
Azim Khan8d686bf2018-07-04 23:29:46 +01001044def main():
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001045 """
1046 Command line parser.
1047
1048 :return:
1049 """
Azim Khan040b6a22018-06-28 16:49:13 +01001050 parser = argparse.ArgumentParser(
Azim Khane3b26af2018-06-29 02:36:57 +01001051 description='Dynamically generate test suite code.')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001052
1053 parser.add_argument("-f", "--functions-file",
1054 dest="funcs_file",
1055 help="Functions file",
Azim Khane3b26af2018-06-29 02:36:57 +01001056 metavar="FUNCTIONS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001057 required=True)
1058
1059 parser.add_argument("-d", "--data-file",
1060 dest="data_file",
1061 help="Data file",
Azim Khane3b26af2018-06-29 02:36:57 +01001062 metavar="DATA_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001063 required=True)
1064
1065 parser.add_argument("-t", "--template-file",
1066 dest="template_file",
1067 help="Template file",
Azim Khane3b26af2018-06-29 02:36:57 +01001068 metavar="TEMPLATE_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001069 required=True)
1070
1071 parser.add_argument("-s", "--suites-dir",
1072 dest="suites_dir",
1073 help="Suites dir",
Azim Khane3b26af2018-06-29 02:36:57 +01001074 metavar="SUITES_DIR",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001075 required=True)
1076
Azim Khane3b26af2018-06-29 02:36:57 +01001077 parser.add_argument("--helpers-file",
1078 dest="helpers_file",
1079 help="Helpers file",
1080 metavar="HELPERS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001081 required=True)
1082
1083 parser.add_argument("-p", "--platform-file",
1084 dest="platform_file",
1085 help="Platform code file",
1086 metavar="PLATFORM_FILE",
1087 required=True)
1088
1089 parser.add_argument("-o", "--out-dir",
1090 dest="out_dir",
1091 help="Dir where generated code and scripts are copied",
1092 metavar="OUT_DIR",
1093 required=True)
1094
1095 args = parser.parse_args()
1096
1097 data_file_name = os.path.basename(args.data_file)
1098 data_name = os.path.splitext(data_file_name)[0]
1099
1100 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +01001101 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001102
1103 out_c_file_dir = os.path.dirname(out_c_file)
1104 out_data_file_dir = os.path.dirname(out_data_file)
Azim Khanb31aa442018-07-03 11:57:54 +01001105 for directory in [out_c_file_dir, out_data_file_dir]:
1106 if not os.path.exists(directory):
1107 os.makedirs(directory)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001108
Azim Khanb31aa442018-07-03 11:57:54 +01001109 generate_code(funcs_file=args.funcs_file, data_file=args.data_file,
1110 template_file=args.template_file,
1111 platform_file=args.platform_file,
1112 helpers_file=args.helpers_file, suites_dir=args.suites_dir,
1113 c_file=out_c_file, out_data_file=out_data_file)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001114
1115
1116if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +01001117 try:
Azim Khan8d686bf2018-07-04 23:29:46 +01001118 main()
Azim Khanb31aa442018-07-03 11:57:54 +01001119 except GeneratorInputError as err:
1120 print("%s: input error: %s" %
1121 (os.path.basename(sys.argv[0]), str(err)))