blob: b01bd3511b6d01c54444c43320c7dcd7af09d2f5 [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!')
635 out = []
636 part = ''
637 escape = False
Azim Khanb31aa442018-07-03 11:57:54 +0100638 for character in inp_str:
639 if not escape and character == split_char:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100640 out.append(part)
641 part = ''
642 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100643 part += character
644 escape = not escape and character == '\\'
645 if part:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100646 out.append(part)
647 return out
648
649
Azim Khanb31aa442018-07-03 11:57:54 +0100650def parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100651 """
Azim Khane3b26af2018-06-29 02:36:57 +0100652 Parses .data file for each test case name, test function name,
653 test dependencies and test arguments. This information is
654 correlated with the test functions file for generating an
655 intermediate data file replacing the strings for test function
656 names, dependencies and integer constant expressions with
657 identifiers. Mainly for optimising space for on-target
658 execution.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100659
Azim Khanf0e42fb2017-08-02 14:47:13 +0100660 :param data_f: file object of the data file.
Azim Khan040b6a22018-06-28 16:49:13 +0100661 :return: Generator that yields test name, function name,
662 dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100663 """
Azim Khanb31aa442018-07-03 11:57:54 +0100664 __state_read_name = 0
665 __state_read_args = 1
666 state = __state_read_name
667 dependencies = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100668 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100669 for line in data_f:
670 line = line.strip()
Azim Khan8d686bf2018-07-04 23:29:46 +0100671 # Skip comments
672 if line.startswith('#'):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100673 continue
674
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100675 # Blank line indicates end of test
Azim Khanb31aa442018-07-03 11:57:54 +0100676 if not line:
677 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100678 raise GeneratorInputError("[%s:%d] Newline before arguments. "
679 "Test function and arguments "
680 "missing for %s" %
681 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100682 continue
683
Azim Khanb31aa442018-07-03 11:57:54 +0100684 if state == __state_read_name:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100685 # Read test name
686 name = line
Azim Khanb31aa442018-07-03 11:57:54 +0100687 state = __state_read_args
688 elif state == __state_read_args:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100689 # Check dependencies
Azim Khan8d686bf2018-07-04 23:29:46 +0100690 match = re.search(DEPENDENCY_REGEX, line)
Azim Khanb31aa442018-07-03 11:57:54 +0100691 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100692 try:
693 dependencies = parse_dependencies(
694 match.group('dependencies'))
695 except GeneratorInputError as error:
696 raise GeneratorInputError(
697 str(error) + " - %s:%d" %
698 (data_f.name, data_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100699 else:
700 # Read test vectors
701 parts = escaped_split(line, ':')
Azim Khanb31aa442018-07-03 11:57:54 +0100702 test_function = parts[0]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100703 args = parts[1:]
Azim Khanb31aa442018-07-03 11:57:54 +0100704 yield name, test_function, dependencies, args
705 dependencies = []
706 state = __state_read_name
707 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100708 raise GeneratorInputError("[%s:%d] Newline before arguments. "
709 "Test function and arguments missing for "
710 "%s" % (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100711
712
713def gen_dep_check(dep_id, dep):
714 """
Azim Khane3b26af2018-06-29 02:36:57 +0100715 Generate code for checking dependency with the associated
716 identifier.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100717
Azim Khanf0e42fb2017-08-02 14:47:13 +0100718 :param dep_id: Dependency identifier
719 :param dep: Dependency macro
720 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100721 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100722 if dep_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100723 raise GeneratorInputError("Dependency Id should be a positive "
724 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100725 _not, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
726 if not dep:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100727 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100728 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100729 case {id}:
730 {{
Azim Khanb31aa442018-07-03 11:57:54 +0100731#if {_not}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100732 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100733#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100734 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100735#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100736 }}
Azim Khanb31aa442018-07-03 11:57:54 +0100737 break;'''.format(_not=_not, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100738 return dep_check
739
740
741def gen_expression_check(exp_id, exp):
742 """
Azim Khane3b26af2018-06-29 02:36:57 +0100743 Generates code for evaluating an integer expression using
744 associated expression Id.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100745
Azim Khanf0e42fb2017-08-02 14:47:13 +0100746 :param exp_id: Expression Identifier
747 :param exp: Expression/Macro
748 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100749 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100750 if exp_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100751 raise GeneratorInputError("Expression Id should be a positive "
752 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100753 if not exp:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100754 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100755 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100756 case {exp_id}:
757 {{
758 *out_value = {expression};
759 }}
760 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100761 return exp_code
762
763
Azim Khanb31aa442018-07-03 11:57:54 +0100764def write_dependencies(out_data_f, test_dependencies, unique_dependencies):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100765 """
Azim Khane3b26af2018-06-29 02:36:57 +0100766 Write dependencies to intermediate test data file, replacing
767 the string form with identifiers. Also, generates dependency
768 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100769
Azim Khanf0e42fb2017-08-02 14:47:13 +0100770 :param out_data_f: Output intermediate data file
Azim Khanb31aa442018-07-03 11:57:54 +0100771 :param test_dependencies: Dependencies
772 :param unique_dependencies: Mutable list to track unique dependencies
Azim Khan040b6a22018-06-28 16:49:13 +0100773 that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100774 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100775 """
Azim Khan599cd242017-07-06 17:34:27 +0100776 dep_check_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100777 if test_dependencies:
Azim Khan599cd242017-07-06 17:34:27 +0100778 out_data_f.write('depends_on')
Azim Khanb31aa442018-07-03 11:57:54 +0100779 for dep in test_dependencies:
780 if dep not in unique_dependencies:
781 unique_dependencies.append(dep)
782 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100783 dep_check_code += gen_dep_check(dep_id, dep)
784 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100785 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100786 out_data_f.write(':' + str(dep_id))
787 out_data_f.write('\n')
788 return dep_check_code
789
790
791def write_parameters(out_data_f, test_args, func_args, unique_expressions):
792 """
Azim Khane3b26af2018-06-29 02:36:57 +0100793 Writes test parameters to the intermediate data file, replacing
794 the string form with identifiers. Also, generates expression
795 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100796
Azim Khanf0e42fb2017-08-02 14:47:13 +0100797 :param out_data_f: Output intermediate data file
798 :param test_args: Test parameters
799 :param func_args: Function arguments
Azim Khan040b6a22018-06-28 16:49:13 +0100800 :param unique_expressions: Mutable list to track unique
801 expressions that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100802 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100803 """
804 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100805 for i, _ in enumerate(test_args):
Azim Khan599cd242017-07-06 17:34:27 +0100806 typ = func_args[i]
807 val = test_args[i]
808
Azim Khan040b6a22018-06-28 16:49:13 +0100809 # check if val is a non literal int val (i.e. an expression)
Azim Khan8d686bf2018-07-04 23:29:46 +0100810 if typ == 'int' and not re.match(r'(\d+|0x[0-9a-f]+)$',
811 val, re.I):
Azim Khan599cd242017-07-06 17:34:27 +0100812 typ = 'exp'
813 if val not in unique_expressions:
814 unique_expressions.append(val)
Azim Khan040b6a22018-06-28 16:49:13 +0100815 # exp_id can be derived from len(). But for
816 # readability and consistency with case of existing
817 # let's use index().
Azim Khan599cd242017-07-06 17:34:27 +0100818 exp_id = unique_expressions.index(val)
819 expression_code += gen_expression_check(exp_id, val)
820 val = exp_id
821 else:
822 val = unique_expressions.index(val)
823 out_data_f.write(':' + typ + ':' + str(val))
824 out_data_f.write('\n')
825 return expression_code
826
827
Azim Khanb31aa442018-07-03 11:57:54 +0100828def gen_suite_dep_checks(suite_dependencies, dep_check_code, expression_code):
Azim Khan599cd242017-07-06 17:34:27 +0100829 """
Azim Khane3b26af2018-06-29 02:36:57 +0100830 Generates preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100831
Azim Khanb31aa442018-07-03 11:57:54 +0100832 :param suite_dependencies: Test suite dependencies read from the
Azim Khan8d686bf2018-07-04 23:29:46 +0100833 .function file.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100834 :param dep_check_code: Dependency check code
835 :param expression_code: Expression check code
Azim Khan040b6a22018-06-28 16:49:13 +0100836 :return: Dependency and expression code guarded by test suite
837 dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100838 """
Azim Khanb31aa442018-07-03 11:57:54 +0100839 if suite_dependencies:
840 preprocessor_check = gen_dependencies_one_line(suite_dependencies)
Azim Khan599cd242017-07-06 17:34:27 +0100841 dep_check_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100842{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100843{code}
Azim Khan599cd242017-07-06 17:34:27 +0100844#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100845'''.format(preprocessor_check=preprocessor_check, code=dep_check_code)
Azim Khan599cd242017-07-06 17:34:27 +0100846 expression_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100847{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100848{code}
Azim Khan599cd242017-07-06 17:34:27 +0100849#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100850'''.format(preprocessor_check=preprocessor_check, code=expression_code)
Azim Khan599cd242017-07-06 17:34:27 +0100851 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100852
853
Azim Khanb31aa442018-07-03 11:57:54 +0100854def gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100855 """
Azim Khane3b26af2018-06-29 02:36:57 +0100856 This function reads test case name, dependencies and test vectors
857 from the .data file. This information is correlated with the test
858 functions file for generating an intermediate data file replacing
859 the strings for test function names, dependencies and integer
860 constant expressions with identifiers. Mainly for optimising
861 space for on-target execution.
862 It also generates test case dependency check code and expression
863 evaluation code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100864
Azim Khanf0e42fb2017-08-02 14:47:13 +0100865 :param data_f: Data file object
Azim Khan8d686bf2018-07-04 23:29:46 +0100866 :param out_data_f: Output intermediate data file
Azim Khan040b6a22018-06-28 16:49:13 +0100867 :param func_info: Dict keyed by function and with function id
868 and arguments info
Azim Khanb31aa442018-07-03 11:57:54 +0100869 :param suite_dependencies: Test suite dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100870 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100871 """
Azim Khanb31aa442018-07-03 11:57:54 +0100872 unique_dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100873 unique_expressions = []
874 dep_check_code = ''
875 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100876 for test_name, function_name, test_dependencies, test_args in \
877 parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100878 out_data_f.write(test_name + '\n')
879
Azim Khanb31aa442018-07-03 11:57:54 +0100880 # Write dependencies
881 dep_check_code += write_dependencies(out_data_f, test_dependencies,
882 unique_dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100883
Azim Khan599cd242017-07-06 17:34:27 +0100884 # Write test function name
885 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100886 if test_function_name not in func_info:
Azim Khan040b6a22018-06-28 16:49:13 +0100887 raise GeneratorInputError("Function %s not found!" %
888 test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100889 func_id, func_args = func_info[test_function_name]
890 out_data_f.write(str(func_id))
891
892 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100893 if len(test_args) != len(func_args):
Azim Khan040b6a22018-06-28 16:49:13 +0100894 raise GeneratorInputError("Invalid number of arguments in test "
Azim Khanb31aa442018-07-03 11:57:54 +0100895 "%s. See function %s signature." %
896 (test_name, function_name))
Azim Khan040b6a22018-06-28 16:49:13 +0100897 expression_code += write_parameters(out_data_f, test_args, func_args,
898 unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100899
Azim Khan599cd242017-07-06 17:34:27 +0100900 # Write a newline as test case separator
901 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100902
Azim Khanb31aa442018-07-03 11:57:54 +0100903 dep_check_code, expression_code = gen_suite_dep_checks(
904 suite_dependencies, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100905 return dep_check_code, expression_code
906
907
Azim Khanb31aa442018-07-03 11:57:54 +0100908def add_input_info(funcs_file, data_file, template_file,
909 c_file, snippets):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100910 """
Azim Khanb31aa442018-07-03 11:57:54 +0100911 Add generator input info in snippets.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100912
Azim Khanf0e42fb2017-08-02 14:47:13 +0100913 :param funcs_file: Functions file object
914 :param data_file: Data file object
915 :param template_file: Template file object
Azim Khanf0e42fb2017-08-02 14:47:13 +0100916 :param c_file: Output C file object
Azim Khanb31aa442018-07-03 11:57:54 +0100917 :param snippets: Dictionary to contain code pieces to be
918 substituted in the template.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100919 :return:
920 """
Azim Khanb31aa442018-07-03 11:57:54 +0100921 snippets['test_file'] = c_file
922 snippets['test_main_file'] = template_file
923 snippets['test_case_file'] = funcs_file
924 snippets['test_case_data_file'] = data_file
925
926
927def read_code_from_input_files(platform_file, helpers_file,
928 out_data_file, snippets):
929 """
930 Read code from input files and create substitutions for replacement
931 strings in the template file.
932
933 :param platform_file: Platform file object
934 :param helpers_file: Helper functions file object
935 :param out_data_file: Output intermediate data file object
936 :param snippets: Dictionary to contain code pieces to be
937 substituted in the template.
938 :return:
939 """
940 # Read helpers
941 with open(helpers_file, 'r') as help_f, open(platform_file, 'r') as \
942 platform_f:
943 snippets['test_common_helper_file'] = helpers_file
944 snippets['test_common_helpers'] = help_f.read()
945 snippets['test_platform_file'] = platform_file
946 snippets['platform_code'] = platform_f.read().replace(
947 'DATA_FILE', out_data_file.replace('\\', '\\\\')) # escape '\'
948
949
950def write_test_source_file(template_file, c_file, snippets):
951 """
952 Write output source file with generated source code.
953
954 :param template_file: Template file name
955 :param c_file: Output source file
956 :param snippets: Generated and code snippets
957 :return:
958 """
959 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
960 line_no = 1
961 for line in template_f.readlines():
962 # Update line number. +1 as #line directive sets next line number
963 snippets['line_no'] = line_no + 1
964 code = line.format(**snippets)
965 c_f.write(code)
966 line_no += 1
967
968
969def parse_function_file(funcs_file, snippets):
970 """
971 Parse function file and generate function dispatch code.
972
973 :param funcs_file: Functions file name
974 :param snippets: Dictionary to contain code pieces to be
975 substituted in the template.
976 :return:
977 """
978 with FileWrapper(funcs_file) as funcs_f:
979 suite_dependencies, dispatch_code, func_code, func_info = \
980 parse_functions(funcs_f)
981 snippets['functions_code'] = func_code
982 snippets['dispatch_code'] = dispatch_code
983 return suite_dependencies, func_info
984
985
986def generate_intermediate_data_file(data_file, out_data_file,
987 suite_dependencies, func_info, snippets):
988 """
989 Generates intermediate data file from input data file and
990 information read from functions file.
991
992 :param data_file: Data file name
993 :param out_data_file: Output/Intermediate data file
994 :param suite_dependencies: List of suite dependencies.
995 :param func_info: Function info parsed from functions file.
996 :param snippets: Dictionary to contain code pieces to be
997 substituted in the template.
998 :return:
999 """
1000 with FileWrapper(data_file) as data_f, \
1001 open(out_data_file, 'w') as out_data_f:
1002 dep_check_code, expression_code = gen_from_test_data(
1003 data_f, out_data_f, func_info, suite_dependencies)
1004 snippets['dep_check_code'] = dep_check_code
1005 snippets['expression_code'] = expression_code
1006
1007
1008def generate_code(**input_info):
1009 """
1010 Generates C source code from test suite file, data file, common
1011 helpers file and platform file.
1012
1013 input_info expands to following parameters:
1014 funcs_file: Functions file object
1015 data_file: Data file object
1016 template_file: Template file object
1017 platform_file: Platform file object
1018 helpers_file: Helper functions file object
1019 suites_dir: Test suites dir
1020 c_file: Output C file object
1021 out_data_file: Output intermediate data file object
1022 :return:
1023 """
1024 funcs_file = input_info['funcs_file']
1025 data_file = input_info['data_file']
1026 template_file = input_info['template_file']
1027 platform_file = input_info['platform_file']
1028 helpers_file = input_info['helpers_file']
1029 suites_dir = input_info['suites_dir']
1030 c_file = input_info['c_file']
1031 out_data_file = input_info['out_data_file']
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001032 for name, path in [('Functions file', funcs_file),
1033 ('Data file', data_file),
1034 ('Template file', template_file),
1035 ('Platform file', platform_file),
Azim Khane3b26af2018-06-29 02:36:57 +01001036 ('Helpers code file', helpers_file),
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001037 ('Suites dir', suites_dir)]:
1038 if not os.path.exists(path):
1039 raise IOError("ERROR: %s [%s] not found!" % (name, path))
1040
Azim Khanb31aa442018-07-03 11:57:54 +01001041 snippets = {'generator_script': os.path.basename(__file__)}
1042 read_code_from_input_files(platform_file, helpers_file,
1043 out_data_file, snippets)
1044 add_input_info(funcs_file, data_file, template_file,
1045 c_file, snippets)
1046 suite_dependencies, func_info = parse_function_file(funcs_file, snippets)
1047 generate_intermediate_data_file(data_file, out_data_file,
1048 suite_dependencies, func_info, snippets)
1049 write_test_source_file(template_file, c_file, snippets)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001050
1051
Azim Khan8d686bf2018-07-04 23:29:46 +01001052def main():
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001053 """
1054 Command line parser.
1055
1056 :return:
1057 """
Azim Khan040b6a22018-06-28 16:49:13 +01001058 parser = argparse.ArgumentParser(
Azim Khane3b26af2018-06-29 02:36:57 +01001059 description='Dynamically generate test suite code.')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001060
1061 parser.add_argument("-f", "--functions-file",
1062 dest="funcs_file",
1063 help="Functions file",
Azim Khane3b26af2018-06-29 02:36:57 +01001064 metavar="FUNCTIONS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001065 required=True)
1066
1067 parser.add_argument("-d", "--data-file",
1068 dest="data_file",
1069 help="Data file",
Azim Khane3b26af2018-06-29 02:36:57 +01001070 metavar="DATA_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001071 required=True)
1072
1073 parser.add_argument("-t", "--template-file",
1074 dest="template_file",
1075 help="Template file",
Azim Khane3b26af2018-06-29 02:36:57 +01001076 metavar="TEMPLATE_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001077 required=True)
1078
1079 parser.add_argument("-s", "--suites-dir",
1080 dest="suites_dir",
1081 help="Suites dir",
Azim Khane3b26af2018-06-29 02:36:57 +01001082 metavar="SUITES_DIR",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001083 required=True)
1084
Azim Khane3b26af2018-06-29 02:36:57 +01001085 parser.add_argument("--helpers-file",
1086 dest="helpers_file",
1087 help="Helpers file",
1088 metavar="HELPERS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001089 required=True)
1090
1091 parser.add_argument("-p", "--platform-file",
1092 dest="platform_file",
1093 help="Platform code file",
1094 metavar="PLATFORM_FILE",
1095 required=True)
1096
1097 parser.add_argument("-o", "--out-dir",
1098 dest="out_dir",
1099 help="Dir where generated code and scripts are copied",
1100 metavar="OUT_DIR",
1101 required=True)
1102
1103 args = parser.parse_args()
1104
1105 data_file_name = os.path.basename(args.data_file)
1106 data_name = os.path.splitext(data_file_name)[0]
1107
1108 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +01001109 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001110
1111 out_c_file_dir = os.path.dirname(out_c_file)
1112 out_data_file_dir = os.path.dirname(out_data_file)
Azim Khanb31aa442018-07-03 11:57:54 +01001113 for directory in [out_c_file_dir, out_data_file_dir]:
1114 if not os.path.exists(directory):
1115 os.makedirs(directory)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001116
Azim Khanb31aa442018-07-03 11:57:54 +01001117 generate_code(funcs_file=args.funcs_file, data_file=args.data_file,
1118 template_file=args.template_file,
1119 platform_file=args.platform_file,
1120 helpers_file=args.helpers_file, suites_dir=args.suites_dir,
1121 c_file=out_c_file, out_data_file=out_data_file)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001122
1123
1124if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +01001125 try:
Azim Khan8d686bf2018-07-04 23:29:46 +01001126 main()
Azim Khanb31aa442018-07-03 11:57:54 +01001127 except GeneratorInputError as err:
1128 print("%s: input error: %s" %
1129 (os.path.basename(sys.argv[0]), str(err)))