blob: 26d1c29cb3cf973c13d27931572aac38687cdd37 [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
Mohammad Azim Khand2d01122018-07-18 17:48:37 +010060 AES 128 GCM Encrypt and decrypt 8 bytes
61 depends_on:MBEDTLS_AES_C:MBEDTLS_GCM_C
62 enc_dec_buf:MBEDTLS_CIPHER_AES_128_GCM:"AES-128-GCM":128:8:-1
Azim Khanaee05bb2018-07-02 16:01:04 +010063
64Test functions:
65---------------
66Test functions are coded in C in test_suite_<module>.function files.
67Functions file is itself not compilable and contains special
68format patterns to specify test suite dependencies, start and end
69of functions and function dependencies. Check any existing functions
70file for example.
71
72Execution:
73----------
74Tests are executed in 3 steps:
75- Generating test_suite_<module>[.<optional sub module>].c file
76 for each corresponding .data file.
77- Building each source file into executables.
78- Running each executable and printing report.
79
80Generating C test source requires more than just the test functions.
81Following extras are required:
82- Process main()
83- Reading .data file and dispatching test cases.
84- Platform specific test case execution
85- Dependency checking
86- Integer expression evaluation
87- Test function dispatch
88
89Build dependencies and integer expressions (in the test parameters)
90are specified as strings in the .data file. Their run time value is
91not known at the generation stage. Hence, they need to be translated
92into run time evaluations. This script generates the run time checks
93for dependencies and integer expressions.
94
95Similarly, function names have to be translated into function calls.
96This script also generates code for function dispatch.
97
98The extra code mentioned here is either generated by this script
99or it comes from the input files: helpers file, platform file and
100the template file.
101
102Helper file:
103------------
104Helpers file contains common helper/utility functions and data.
105
106Platform file:
107--------------
108Platform file contains platform specific setup code and test case
109dispatch code. For example, host_test.function reads test data
110file from host's file system and dispatches tests.
111In case of on-target target_test.function tests are not dispatched
112on target. Target code is kept minimum and only test functions are
113dispatched. Test case dispatch is done on the host using tools like
114Greentea.
115
116Template file:
117---------
118Template file for example main_test.function is a template C file in
119which generated code and code from input files is substituted to
120generate a compilable C file. It also contains skeleton functions for
121dependency checks, expression evaluation and function dispatch. These
122functions are populated with checks and return codes by this script.
123
124Template file contains "replacement" fields that are formatted
125strings processed by Python str.format() method.
126
127This script:
128============
129Core function of this script is to fill the template file with
130code that is generated or read from helpers and platform files.
131
132This script replaces following fields in the template and generates
133the test source file:
134
135{test_common_helpers} <-- All common code from helpers.function
136 is substituted here.
137{functions_code} <-- Test functions are substituted here
138 from the input test_suit_xyz.function
139 file. C preprocessor checks are generated
140 for the build dependencies specified
141 in the input file. This script also
142 generates wrappers for the test
143 functions with code to expand the
144 string parameters read from the data
145 file.
146{expression_code} <-- This script enumerates the
147 expressions in the .data file and
148 generates code to handle enumerated
149 expression Ids and return the values.
150{dep_check_code} <-- This script enumerates all
151 build dependencies and generate
152 code to handle enumerated build
153 dependency Id and return status: if
154 the dependency is defined or not.
155{dispatch_code} <-- This script enumerates the functions
156 specified in the input test data file
157 and generates the initializer for the
158 function table in the template
159 file.
160{platform_code} <-- Platform specific setup and test
161 dispatch code.
162
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100163"""
164
Azim Khanf0e42fb2017-08-02 14:47:13 +0100165
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100166import io
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100167import os
168import re
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100169import sys
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100170import argparse
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100171
172
Azim Khanb31aa442018-07-03 11:57:54 +0100173BEGIN_HEADER_REGEX = r'/\*\s*BEGIN_HEADER\s*\*/'
174END_HEADER_REGEX = r'/\*\s*END_HEADER\s*\*/'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100175
Azim Khanb31aa442018-07-03 11:57:54 +0100176BEGIN_SUITE_HELPERS_REGEX = r'/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
177END_SUITE_HELPERS_REGEX = r'/\*\s*END_SUITE_HELPERS\s*\*/'
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000178
Azim Khanb31aa442018-07-03 11:57:54 +0100179BEGIN_DEP_REGEX = r'BEGIN_DEPENDENCIES'
180END_DEP_REGEX = r'END_DEPENDENCIES'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100181
Azim Khan8d686bf2018-07-04 23:29:46 +0100182BEGIN_CASE_REGEX = r'/\*\s*BEGIN_CASE\s*(?P<depends_on>.*?)\s*\*/'
Azim Khanb31aa442018-07-03 11:57:54 +0100183END_CASE_REGEX = r'/\*\s*END_CASE\s*\*/'
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100184
Azim Khan8d686bf2018-07-04 23:29:46 +0100185DEPENDENCY_REGEX = r'depends_on:(?P<dependencies>.*)'
Mohammad Azim Khan440d8732018-07-18 12:50:49 +0100186C_IDENTIFIER_REGEX = r'!?[a-z_][a-z0-9_]*$'
Azim Khanfcdf6852018-07-05 17:31:46 +0100187TEST_FUNCTION_VALIDATION_REGEX = r'\s*void\s+(?P<func_name>\w+)\s*\('
Azim Khan8d686bf2018-07-04 23:29:46 +0100188INT_CHECK_REGEX = r'int\s+.*'
189CHAR_CHECK_REGEX = r'char\s*\*\s*.*'
190DATA_T_CHECK_REGEX = r'data_t\s*\*\s*.*'
Azim Khan8d686bf2018-07-04 23:29:46 +0100191FUNCTION_ARG_LIST_END_REGEX = r'.*\)'
192EXIT_LABEL_REGEX = r'^exit:'
193
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100194
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100195class GeneratorInputError(Exception):
196 """
Azim Khane3b26af2018-06-29 02:36:57 +0100197 Exception to indicate error in the input files to this script.
198 This includes missing patterns, test function names and other
199 parsing errors.
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100200 """
201 pass
202
203
Azim Khanb31aa442018-07-03 11:57:54 +0100204class FileWrapper(io.FileIO, object):
Azim Khan4b543232017-06-30 09:35:21 +0100205 """
Azim Khane3b26af2018-06-29 02:36:57 +0100206 This class extends built-in io.FileIO class with attribute line_no,
207 that indicates line number for the line that is read.
Azim Khan4b543232017-06-30 09:35:21 +0100208 """
209
210 def __init__(self, file_name):
211 """
Azim Khane3b26af2018-06-29 02:36:57 +0100212 Instantiate the base class and initialize the line number to 0.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100213
Azim Khanf0e42fb2017-08-02 14:47:13 +0100214 :param file_name: File path to open.
Azim Khan4b543232017-06-30 09:35:21 +0100215 """
216 super(FileWrapper, self).__init__(file_name, 'r')
Azim Khanb31aa442018-07-03 11:57:54 +0100217 self._line_no = 0
Azim Khan4b543232017-06-30 09:35:21 +0100218
Azim Khanb31aa442018-07-03 11:57:54 +0100219 def next(self):
Azim Khan4b543232017-06-30 09:35:21 +0100220 """
Azim Khane3b26af2018-06-29 02:36:57 +0100221 Python 2 iterator method. This method overrides base class's
222 next method and extends the next method to count the line
223 numbers as each line is read.
224
225 It works for both Python 2 and Python 3 by checking iterator
226 method name in the base iterator object.
227
Azim Khanf0e42fb2017-08-02 14:47:13 +0100228 :return: Line read from file.
Azim Khan4b543232017-06-30 09:35:21 +0100229 """
Gilles Peskine667f7f82018-06-18 17:51:56 +0200230 parent = super(FileWrapper, self)
231 if hasattr(parent, '__next__'):
Azim Khanb31aa442018-07-03 11:57:54 +0100232 line = parent.__next__() # Python 3
Gilles Peskine667f7f82018-06-18 17:51:56 +0200233 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100234 line = parent.next() # Python 2
235 if line is not None:
236 self._line_no += 1
Azim Khan936ea932018-06-28 16:47:12 +0100237 # Convert byte array to string with correct encoding and
238 # strip any whitespaces added in the decoding process.
Azim Khan8d686bf2018-07-04 23:29:46 +0100239 return line.decode(sys.getdefaultencoding()).rstrip() + '\n'
Mohammad Azim Khan1ec7e6f2018-04-11 23:46:37 +0100240 return None
Azim Khane3b26af2018-06-29 02:36:57 +0100241
242 # Python 3 iterator method
Azim Khanb31aa442018-07-03 11:57:54 +0100243 __next__ = next
244
245 def get_line_no(self):
246 """
247 Gives current line number.
248 """
249 return self._line_no
250
251 line_no = property(get_line_no)
Azim Khan4b543232017-06-30 09:35:21 +0100252
253
254def split_dep(dep):
Azim Khanf0e42fb2017-08-02 14:47:13 +0100255 """
Azim Khanb31aa442018-07-03 11:57:54 +0100256 Split NOT character '!' from dependency. Used by gen_dependencies()
Azim Khanf0e42fb2017-08-02 14:47:13 +0100257
258 :param dep: Dependency list
Azim Khane3b26af2018-06-29 02:36:57 +0100259 :return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
260 MACRO.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100261 """
Azim Khan4b543232017-06-30 09:35:21 +0100262 return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
263
264
Azim Khanb31aa442018-07-03 11:57:54 +0100265def gen_dependencies(dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100266 """
Azim Khane3b26af2018-06-29 02:36:57 +0100267 Test suite data and functions specifies compile time dependencies.
268 This function generates C preprocessor code from the input
269 dependency list. Caller uses the generated preprocessor code to
270 wrap dependent code.
271 A dependency in the input list can have a leading '!' character
272 to negate a condition. '!' is separated from the dependency using
273 function split_dep() and proper preprocessor check is generated
274 accordingly.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100275
Azim Khanb31aa442018-07-03 11:57:54 +0100276 :param dependencies: List of dependencies.
Azim Khan040b6a22018-06-28 16:49:13 +0100277 :return: if defined and endif code with macro annotations for
278 readability.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100279 """
Azim Khanb31aa442018-07-03 11:57:54 +0100280 dep_start = ''.join(['#if %sdefined(%s)\n' % (x, y) for x, y in
281 map(split_dep, dependencies)])
282 dep_end = ''.join(['#endif /* %s */\n' %
283 x for x in reversed(dependencies)])
Azim Khan4b543232017-06-30 09:35:21 +0100284
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100285 return dep_start, dep_end
286
287
Azim Khanb31aa442018-07-03 11:57:54 +0100288def gen_dependencies_one_line(dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100289 """
Azim Khanb31aa442018-07-03 11:57:54 +0100290 Similar to gen_dependencies() but generates dependency checks in one line.
Azim Khane3b26af2018-06-29 02:36:57 +0100291 Useful for generating code with #else block.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100292
Azim Khanb31aa442018-07-03 11:57:54 +0100293 :param dependencies: List of dependencies.
294 :return: Preprocessor check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100295 """
Azim Khanb31aa442018-07-03 11:57:54 +0100296 defines = '#if ' if dependencies else ''
297 defines += ' && '.join(['%sdefined(%s)' % (x, y) for x, y in map(
298 split_dep, dependencies)])
Azim Khan4b543232017-06-30 09:35:21 +0100299 return defines
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100300
301
Azim Khanb31aa442018-07-03 11:57:54 +0100302def gen_function_wrapper(name, local_vars, args_dispatch):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100303 """
Azim Khan040b6a22018-06-28 16:49:13 +0100304 Creates test function wrapper code. A wrapper has the code to
305 unpack parameters from parameters[] array.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100306
Azim Khanf0e42fb2017-08-02 14:47:13 +0100307 :param name: Test function name
Azim Khanb31aa442018-07-03 11:57:54 +0100308 :param local_vars: Local variables declaration code
Azim Khan040b6a22018-06-28 16:49:13 +0100309 :param args_dispatch: List of dispatch arguments.
310 Ex: ['(char *)params[0]', '*((int *)params[1])']
Azim Khanf0e42fb2017-08-02 14:47:13 +0100311 :return: Test function wrapper.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100312 """
313 # Then create the wrapper
314 wrapper = '''
315void {name}_wrapper( void ** params )
316{{
Gilles Peskine77761412018-06-18 17:51:40 +0200317{unused_params}{locals}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100318 {name}( {args} );
319}}
Gilles Peskine77761412018-06-18 17:51:40 +0200320'''.format(name=name,
Mohammad Azim Khanc3521df2018-06-26 14:06:52 +0100321 unused_params='' if args_dispatch else ' (void)params;\n',
Azim Khan4b543232017-06-30 09:35:21 +0100322 args=', '.join(args_dispatch),
Azim Khanb31aa442018-07-03 11:57:54 +0100323 locals=local_vars)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100324 return wrapper
325
326
Azim Khanb31aa442018-07-03 11:57:54 +0100327def gen_dispatch(name, dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100328 """
Azim Khane3b26af2018-06-29 02:36:57 +0100329 Test suite code template main_test.function defines a C function
330 array to contain test case functions. This function generates an
331 initializer entry for a function in that array. The entry is
332 composed of a compile time check for the test function
333 dependencies. At compile time the test function is assigned when
334 dependencies are met, else NULL is assigned.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100335
Azim Khanf0e42fb2017-08-02 14:47:13 +0100336 :param name: Test function name
Azim Khanb31aa442018-07-03 11:57:54 +0100337 :param dependencies: List of dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100338 :return: Dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100339 """
Azim Khanb31aa442018-07-03 11:57:54 +0100340 if dependencies:
341 preprocessor_check = gen_dependencies_one_line(dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100342 dispatch_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100343{preprocessor_check}
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100344 {name}_wrapper,
345#else
346 NULL,
347#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100348'''.format(preprocessor_check=preprocessor_check, name=name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100349 else:
350 dispatch_code = '''
351 {name}_wrapper,
352'''.format(name=name)
353
354 return dispatch_code
355
356
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000357def parse_until_pattern(funcs_f, end_regex):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100358 """
Azim Khane3b26af2018-06-29 02:36:57 +0100359 Matches pattern end_regex to the lines read from the file object.
360 Returns the lines read until end pattern is matched.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100361
Azim Khan8d686bf2018-07-04 23:29:46 +0100362 :param funcs_f: file object for .function file
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000363 :param end_regex: Pattern to stop parsing
Azim Khane3b26af2018-06-29 02:36:57 +0100364 :return: Lines read before the end pattern
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100365 """
Azim Khan4b543232017-06-30 09:35:21 +0100366 headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100367 for line in funcs_f:
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000368 if re.search(end_regex, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100369 break
370 headers += line
371 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100372 raise GeneratorInputError("file: %s - end pattern [%s] not found!" %
Azim Khanb31aa442018-07-03 11:57:54 +0100373 (funcs_f.name, end_regex))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100374
Azim Khan4b543232017-06-30 09:35:21 +0100375 return headers
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100376
377
Azim Khan8d686bf2018-07-04 23:29:46 +0100378def validate_dependency(dependency):
379 """
380 Validates a C macro and raises GeneratorInputError on invalid input.
381 :param dependency: Input macro dependency
382 :return: input dependency stripped of leading & trailing white spaces.
383 """
384 dependency = dependency.strip()
385 if not re.match(C_IDENTIFIER_REGEX, dependency, re.I):
386 raise GeneratorInputError('Invalid dependency %s' % dependency)
387 return dependency
388
389
390def parse_dependencies(inp_str):
391 """
392 Parses dependencies out of inp_str, validates them and returns a
393 list of macros.
394
395 :param inp_str: Input string with macros delimited by ':'.
396 :return: list of dependencies
397 """
398 dependencies = [dep for dep in map(validate_dependency,
399 inp_str.split(':'))]
400 return dependencies
401
402
Azim Khanb31aa442018-07-03 11:57:54 +0100403def parse_suite_dependencies(funcs_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100404 """
Azim Khane3b26af2018-06-29 02:36:57 +0100405 Parses test suite dependencies specified at the top of a
406 .function file, that starts with pattern BEGIN_DEPENDENCIES
407 and end with END_DEPENDENCIES. Dependencies are specified
408 after pattern 'depends_on:' and are delimited by ':'.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100409
Azim Khan8d686bf2018-07-04 23:29:46 +0100410 :param funcs_f: file object for .function file
Azim Khanf0e42fb2017-08-02 14:47:13 +0100411 :return: List of test suite dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100412 """
Azim Khanb31aa442018-07-03 11:57:54 +0100413 dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100414 for line in funcs_f:
Azim Khan8d686bf2018-07-04 23:29:46 +0100415 match = re.search(DEPENDENCY_REGEX, line.strip())
Azim Khanb31aa442018-07-03 11:57:54 +0100416 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100417 try:
418 dependencies = parse_dependencies(match.group('dependencies'))
419 except GeneratorInputError as error:
420 raise GeneratorInputError(
421 str(error) + " - %s:%d" % (funcs_f.name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100422 if re.search(END_DEP_REGEX, line):
423 break
424 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100425 raise GeneratorInputError("file: %s - end dependency pattern [%s]"
Azim Khanb31aa442018-07-03 11:57:54 +0100426 " not found!" % (funcs_f.name,
427 END_DEP_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100428
Azim Khanb31aa442018-07-03 11:57:54 +0100429 return dependencies
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100430
431
Azim Khanb31aa442018-07-03 11:57:54 +0100432def parse_function_dependencies(line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100433 """
Azim Khane3b26af2018-06-29 02:36:57 +0100434 Parses function dependencies, that are in the same line as
435 comment BEGIN_CASE. Dependencies are specified after pattern
436 'depends_on:' and are delimited by ':'.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100437
Azim Khan8d686bf2018-07-04 23:29:46 +0100438 :param line: Line from .function file that has dependencies.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100439 :return: List of dependencies.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100440 """
Azim Khanb31aa442018-07-03 11:57:54 +0100441 dependencies = []
442 match = re.search(BEGIN_CASE_REGEX, line)
Azim Khan8d686bf2018-07-04 23:29:46 +0100443 dep_str = match.group('depends_on')
Azim Khanb31aa442018-07-03 11:57:54 +0100444 if dep_str:
Azim Khan8d686bf2018-07-04 23:29:46 +0100445 match = re.search(DEPENDENCY_REGEX, dep_str)
Azim Khanb31aa442018-07-03 11:57:54 +0100446 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100447 dependencies += parse_dependencies(match.group('dependencies'))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100448
Azim Khan8d686bf2018-07-04 23:29:46 +0100449 return dependencies
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100450
Azim Khan4084ec72018-07-05 14:20:08 +0100451
Azim Khanfcdf6852018-07-05 17:31:46 +0100452def parse_function_arguments(line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100453 """
Azim Khane3b26af2018-06-29 02:36:57 +0100454 Parses test function signature for validation and generates
455 a dispatch wrapper function that translates input test vectors
456 read from the data file into test function arguments.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100457
Azim Khan8d686bf2018-07-04 23:29:46 +0100458 :param line: Line from .function file that has a function
Azim Khan040b6a22018-06-28 16:49:13 +0100459 signature.
Azim Khanfcdf6852018-07-05 17:31:46 +0100460 :return: argument list, local variables for
Azim Khan040b6a22018-06-28 16:49:13 +0100461 wrapper function and argument dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100462 """
463 args = []
Azim Khanb31aa442018-07-03 11:57:54 +0100464 local_vars = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100465 args_dispatch = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100466 arg_idx = 0
Azim Khanfcdf6852018-07-05 17:31:46 +0100467 # Remove characters before arguments
468 line = line[line.find('(') + 1:]
Azim Khan8d686bf2018-07-04 23:29:46 +0100469 # Process arguments, ex: <type> arg1, <type> arg2 )
470 # This script assumes that the argument list is terminated by ')'
471 # i.e. the test functions will not have a function pointer
472 # argument.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100473 for arg in line[:line.find(')')].split(','):
474 arg = arg.strip()
475 if arg == '':
476 continue
Azim Khan8d686bf2018-07-04 23:29:46 +0100477 if re.search(INT_CHECK_REGEX, arg.strip()):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100478 args.append('int')
479 args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
Azim Khan8d686bf2018-07-04 23:29:46 +0100480 elif re.search(CHAR_CHECK_REGEX, arg.strip()):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100481 args.append('char*')
482 args_dispatch.append('(char *) params[%d]' % arg_idx)
Azim Khan8d686bf2018-07-04 23:29:46 +0100483 elif re.search(DATA_T_CHECK_REGEX, arg.strip()):
Azim Khana57a4202017-05-31 20:32:32 +0100484 args.append('hex')
Azim Khan2397bba2017-06-09 04:35:03 +0100485 # create a structure
Azim Khan040b6a22018-06-28 16:49:13 +0100486 pointer_initializer = '(uint8_t *) params[%d]' % arg_idx
487 len_initializer = '*( (uint32_t *) params[%d] )' % (arg_idx+1)
Azim Khanb31aa442018-07-03 11:57:54 +0100488 local_vars += """ data_t data%d = {%s, %s};
Azim Khan040b6a22018-06-28 16:49:13 +0100489""" % (arg_idx, pointer_initializer, len_initializer)
Azim Khan2397bba2017-06-09 04:35:03 +0100490
Azim Khan5fcca462018-06-29 11:05:32 +0100491 args_dispatch.append('&data%d' % arg_idx)
Azim Khan2397bba2017-06-09 04:35:03 +0100492 arg_idx += 1
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100493 else:
Azim Khan040b6a22018-06-28 16:49:13 +0100494 raise ValueError("Test function arguments can only be 'int', "
Azim Khan5fcca462018-06-29 11:05:32 +0100495 "'char *' or 'data_t'\n%s" % line)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100496 arg_idx += 1
497
Azim Khanfcdf6852018-07-05 17:31:46 +0100498 return args, local_vars, args_dispatch
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100499
500
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100501def generate_function_code(name, code, local_vars, args_dispatch,
502 dependencies):
503 """
504 Generate function code with preprocessor checks and parameter dispatch
505 wrapper.
506
507 :param name: Function name
508 :param code: Function code
509 :param local_vars: Local variables for function wrapper
510 :param args_dispatch: Argument dispatch code
511 :param dependencies: Preprocessor dependencies list
512 :return: Final function code
513 """
514 # Add exit label if not present
515 if code.find('exit:') == -1:
516 split_code = code.rsplit('}', 1)
517 if len(split_code) == 2:
518 code = """exit:
519 ;
520}""".join(split_code)
521
522 code += gen_function_wrapper(name, local_vars, args_dispatch)
523 preprocessor_check_start, preprocessor_check_end = \
524 gen_dependencies(dependencies)
525 return preprocessor_check_start + code + preprocessor_check_end
526
527
Azim Khanb31aa442018-07-03 11:57:54 +0100528def parse_function_code(funcs_f, dependencies, suite_dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100529 """
Azim Khan040b6a22018-06-28 16:49:13 +0100530 Parses out a function from function file object and generates
531 function and dispatch code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100532
Azim Khanf0e42fb2017-08-02 14:47:13 +0100533 :param funcs_f: file object of the functions file.
Azim Khanb31aa442018-07-03 11:57:54 +0100534 :param dependencies: List of dependencies
535 :param suite_dependencies: List of test suite dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100536 :return: Function name, arguments, function code and dispatch code.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100537 """
Azim Khanfcdf6852018-07-05 17:31:46 +0100538 line_directive = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
539 code = ''
Azim Khan8d686bf2018-07-04 23:29:46 +0100540 has_exit_label = False
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100541 for line in funcs_f:
Azim Khanfcdf6852018-07-05 17:31:46 +0100542 # Check function signature. Function signature may be split
543 # across multiple lines. Here we try to find the start of
544 # arguments list, then remove '\n's and apply the regex to
545 # detect function start.
546 up_to_arg_list_start = code + line[:line.find('(') + 1]
547 match = re.match(TEST_FUNCTION_VALIDATION_REGEX,
548 up_to_arg_list_start.replace('\n', ' '), re.I)
Azim Khanb31aa442018-07-03 11:57:54 +0100549 if match:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100550 # check if we have full signature i.e. split in more lines
Azim Khanfcdf6852018-07-05 17:31:46 +0100551 name = match.group('func_name')
Azim Khan8d686bf2018-07-04 23:29:46 +0100552 if not re.match(FUNCTION_ARG_LIST_END_REGEX, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100553 for lin in funcs_f:
554 line += lin
Azim Khan8d686bf2018-07-04 23:29:46 +0100555 if re.search(FUNCTION_ARG_LIST_END_REGEX, line):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100556 break
Azim Khanfcdf6852018-07-05 17:31:46 +0100557 args, local_vars, args_dispatch = parse_function_arguments(
Azim Khanb31aa442018-07-03 11:57:54 +0100558 line)
Azim Khan8d686bf2018-07-04 23:29:46 +0100559 code += line
Azim Khanfcdf6852018-07-05 17:31:46 +0100560 break
561 code += line
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100562 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100563 raise GeneratorInputError("file: %s - Test functions not found!" %
Azim Khanb31aa442018-07-03 11:57:54 +0100564 funcs_f.name)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100565
Azim Khanfcdf6852018-07-05 17:31:46 +0100566 # Prefix test function name with 'test_'
567 code = code.replace(name, 'test_' + name, 1)
568 name = 'test_' + name
569
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100570 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100571 if re.search(END_CASE_REGEX, line):
572 break
Azim Khan8d686bf2018-07-04 23:29:46 +0100573 if not has_exit_label:
574 has_exit_label = \
575 re.search(EXIT_LABEL_REGEX, line.strip()) is not None
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100576 code += line
577 else:
Azim Khane3b26af2018-06-29 02:36:57 +0100578 raise GeneratorInputError("file: %s - end case pattern [%s] not "
Azim Khanb31aa442018-07-03 11:57:54 +0100579 "found!" % (funcs_f.name, END_CASE_REGEX))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100580
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100581 code = line_directive + code
582 code = generate_function_code(name, code, local_vars, args_dispatch,
583 dependencies)
Azim Khanb31aa442018-07-03 11:57:54 +0100584 dispatch_code = gen_dispatch(name, suite_dependencies + dependencies)
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100585 return (name, args, code, dispatch_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100586
587
588def parse_functions(funcs_f):
589 """
Azim Khane3b26af2018-06-29 02:36:57 +0100590 Parses a test_suite_xxx.function file and returns information
591 for generating a C source file for the test suite.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100592
Azim Khanf0e42fb2017-08-02 14:47:13 +0100593 :param funcs_f: file object of the functions file.
Azim Khan040b6a22018-06-28 16:49:13 +0100594 :return: List of test suite dependencies, test function dispatch
595 code, function code and a dict with function identifiers
596 and arguments info.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100597 """
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000598 suite_helpers = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100599 suite_dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100600 suite_functions = ''
601 func_info = {}
602 function_idx = 0
603 dispatch_code = ''
604 for line in funcs_f:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100605 if re.search(BEGIN_HEADER_REGEX, line):
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100606 suite_helpers += parse_until_pattern(funcs_f, END_HEADER_REGEX)
Mohammad Azim Khanb5229292018-02-06 13:08:01 +0000607 elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100608 suite_helpers += parse_until_pattern(funcs_f,
609 END_SUITE_HELPERS_REGEX)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100610 elif re.search(BEGIN_DEP_REGEX, line):
Azim Khanb31aa442018-07-03 11:57:54 +0100611 suite_dependencies += parse_suite_dependencies(funcs_f)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100612 elif re.search(BEGIN_CASE_REGEX, line):
Azim Khan8d686bf2018-07-04 23:29:46 +0100613 try:
614 dependencies = parse_function_dependencies(line)
615 except GeneratorInputError as error:
616 raise GeneratorInputError(
617 "%s:%d: %s" % (funcs_f.name, funcs_f.line_no,
618 str(error)))
Azim Khan040b6a22018-06-28 16:49:13 +0100619 func_name, args, func_code, func_dispatch =\
Azim Khanb31aa442018-07-03 11:57:54 +0100620 parse_function_code(funcs_f, dependencies, suite_dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100621 suite_functions += func_code
622 # Generate dispatch code and enumeration info
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100623 if func_name in func_info:
624 raise GeneratorInputError(
Azim Khanb31aa442018-07-03 11:57:54 +0100625 "file: %s - function %s re-declared at line %d" %
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100626 (funcs_f.name, func_name, funcs_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100627 func_info[func_name] = (function_idx, args)
628 dispatch_code += '/* Function Id: %d */\n' % function_idx
629 dispatch_code += func_dispatch
630 function_idx += 1
631
Azim Khanb31aa442018-07-03 11:57:54 +0100632 func_code = (suite_helpers +
633 suite_functions).join(gen_dependencies(suite_dependencies))
634 return suite_dependencies, dispatch_code, func_code, func_info
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100635
636
Azim Khanb31aa442018-07-03 11:57:54 +0100637def escaped_split(inp_str, split_char):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100638 """
Azim Khanb31aa442018-07-03 11:57:54 +0100639 Split inp_str on character split_char but ignore if escaped.
Azim Khan040b6a22018-06-28 16:49:13 +0100640 Since, return value is used to write back to the intermediate
641 data file, any escape characters in the input are retained in the
642 output.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100643
Azim Khanb31aa442018-07-03 11:57:54 +0100644 :param inp_str: String to split
Azim Khan8d686bf2018-07-04 23:29:46 +0100645 :param split_char: Split character
Azim Khanf0e42fb2017-08-02 14:47:13 +0100646 :return: List of splits
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100647 """
Azim Khanb31aa442018-07-03 11:57:54 +0100648 if len(split_char) > 1:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100649 raise ValueError('Expected split character. Found string!')
Azim Khan63028132018-07-05 17:53:11 +0100650 out = re.sub(r'(\\.)|' + split_char,
651 lambda m: m.group(1) or '\n', inp_str,
652 len(inp_str)).split('\n')
Mohammad Azim Khan32cbcda2018-07-06 00:29:09 +0100653 out = [x for x in out if x]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100654 return out
655
656
Azim Khanb31aa442018-07-03 11:57:54 +0100657def parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100658 """
Azim Khane3b26af2018-06-29 02:36:57 +0100659 Parses .data file for each test case name, test function name,
660 test dependencies and test arguments. This information is
661 correlated with the test functions file for generating an
662 intermediate data file replacing the strings for test function
663 names, dependencies and integer constant expressions with
664 identifiers. Mainly for optimising space for on-target
665 execution.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100666
Azim Khanf0e42fb2017-08-02 14:47:13 +0100667 :param data_f: file object of the data file.
Azim Khan040b6a22018-06-28 16:49:13 +0100668 :return: Generator that yields test name, function name,
669 dependency list and function argument list.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100670 """
Azim Khanb31aa442018-07-03 11:57:54 +0100671 __state_read_name = 0
672 __state_read_args = 1
673 state = __state_read_name
674 dependencies = []
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100675 name = ''
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100676 for line in data_f:
677 line = line.strip()
Azim Khan8d686bf2018-07-04 23:29:46 +0100678 # Skip comments
679 if line.startswith('#'):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100680 continue
681
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100682 # Blank line indicates end of test
Azim Khanb31aa442018-07-03 11:57:54 +0100683 if not line:
684 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100685 raise GeneratorInputError("[%s:%d] Newline before arguments. "
686 "Test function and arguments "
687 "missing for %s" %
688 (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100689 continue
690
Azim Khanb31aa442018-07-03 11:57:54 +0100691 if state == __state_read_name:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100692 # Read test name
693 name = line
Azim Khanb31aa442018-07-03 11:57:54 +0100694 state = __state_read_args
695 elif state == __state_read_args:
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100696 # Check dependencies
Azim Khan8d686bf2018-07-04 23:29:46 +0100697 match = re.search(DEPENDENCY_REGEX, line)
Azim Khanb31aa442018-07-03 11:57:54 +0100698 if match:
Azim Khan8d686bf2018-07-04 23:29:46 +0100699 try:
700 dependencies = parse_dependencies(
701 match.group('dependencies'))
702 except GeneratorInputError as error:
703 raise GeneratorInputError(
704 str(error) + " - %s:%d" %
705 (data_f.name, data_f.line_no))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100706 else:
707 # Read test vectors
708 parts = escaped_split(line, ':')
Azim Khanb31aa442018-07-03 11:57:54 +0100709 test_function = parts[0]
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100710 args = parts[1:]
Azim Khanb31aa442018-07-03 11:57:54 +0100711 yield name, test_function, dependencies, args
712 dependencies = []
713 state = __state_read_name
714 if state == __state_read_args:
Azim Khan040b6a22018-06-28 16:49:13 +0100715 raise GeneratorInputError("[%s:%d] Newline before arguments. "
716 "Test function and arguments missing for "
717 "%s" % (data_f.name, data_f.line_no, name))
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100718
719
720def gen_dep_check(dep_id, dep):
721 """
Azim Khane3b26af2018-06-29 02:36:57 +0100722 Generate code for checking dependency with the associated
723 identifier.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100724
Azim Khanf0e42fb2017-08-02 14:47:13 +0100725 :param dep_id: Dependency identifier
726 :param dep: Dependency macro
727 :return: Dependency check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100728 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100729 if dep_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100730 raise GeneratorInputError("Dependency Id should be a positive "
731 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100732 _not, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
733 if not dep:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100734 raise GeneratorInputError("Dependency should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100735 dep_check = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100736 case {id}:
737 {{
Azim Khanb31aa442018-07-03 11:57:54 +0100738#if {_not}defined({macro})
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100739 ret = DEPENDENCY_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100740#else
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100741 ret = DEPENDENCY_NOT_SUPPORTED;
Azim Khand61b8372017-07-10 11:54:01 +0100742#endif
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100743 }}
Azim Khanb31aa442018-07-03 11:57:54 +0100744 break;'''.format(_not=_not, macro=dep, id=dep_id)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100745 return dep_check
746
747
748def gen_expression_check(exp_id, exp):
749 """
Azim Khane3b26af2018-06-29 02:36:57 +0100750 Generates code for evaluating an integer expression using
751 associated expression Id.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100752
Azim Khanf0e42fb2017-08-02 14:47:13 +0100753 :param exp_id: Expression Identifier
754 :param exp: Expression/Macro
755 :return: Expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100756 """
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100757 if exp_id < 0:
Azim Khan040b6a22018-06-28 16:49:13 +0100758 raise GeneratorInputError("Expression Id should be a positive "
759 "integer.")
Azim Khanb31aa442018-07-03 11:57:54 +0100760 if not exp:
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100761 raise GeneratorInputError("Expression should not be an empty string.")
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100762 exp_code = '''
Azim Khanb1c2d0f2017-07-07 17:14:02 +0100763 case {exp_id}:
764 {{
765 *out_value = {expression};
766 }}
767 break;'''.format(exp_id=exp_id, expression=exp)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100768 return exp_code
769
770
Azim Khanb31aa442018-07-03 11:57:54 +0100771def write_dependencies(out_data_f, test_dependencies, unique_dependencies):
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100772 """
Azim Khane3b26af2018-06-29 02:36:57 +0100773 Write dependencies to intermediate test data file, replacing
774 the string form with identifiers. Also, generates dependency
775 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100776
Azim Khanf0e42fb2017-08-02 14:47:13 +0100777 :param out_data_f: Output intermediate data file
Azim Khanb31aa442018-07-03 11:57:54 +0100778 :param test_dependencies: Dependencies
779 :param unique_dependencies: Mutable list to track unique dependencies
Azim Khan040b6a22018-06-28 16:49:13 +0100780 that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100781 :return: returns dependency check code.
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100782 """
Azim Khan599cd242017-07-06 17:34:27 +0100783 dep_check_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100784 if test_dependencies:
Azim Khan599cd242017-07-06 17:34:27 +0100785 out_data_f.write('depends_on')
Azim Khanb31aa442018-07-03 11:57:54 +0100786 for dep in test_dependencies:
787 if dep not in unique_dependencies:
788 unique_dependencies.append(dep)
789 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100790 dep_check_code += gen_dep_check(dep_id, dep)
791 else:
Azim Khanb31aa442018-07-03 11:57:54 +0100792 dep_id = unique_dependencies.index(dep)
Azim Khan599cd242017-07-06 17:34:27 +0100793 out_data_f.write(':' + str(dep_id))
794 out_data_f.write('\n')
795 return dep_check_code
796
797
798def write_parameters(out_data_f, test_args, func_args, unique_expressions):
799 """
Azim Khane3b26af2018-06-29 02:36:57 +0100800 Writes test parameters to the intermediate data file, replacing
801 the string form with identifiers. Also, generates expression
802 check code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100803
Azim Khanf0e42fb2017-08-02 14:47:13 +0100804 :param out_data_f: Output intermediate data file
805 :param test_args: Test parameters
806 :param func_args: Function arguments
Azim Khan040b6a22018-06-28 16:49:13 +0100807 :param unique_expressions: Mutable list to track unique
808 expressions that are global to this re-entrant function.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100809 :return: Returns expression check code.
Azim Khan599cd242017-07-06 17:34:27 +0100810 """
811 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100812 for i, _ in enumerate(test_args):
Azim Khan599cd242017-07-06 17:34:27 +0100813 typ = func_args[i]
814 val = test_args[i]
815
Azim Khan040b6a22018-06-28 16:49:13 +0100816 # check if val is a non literal int val (i.e. an expression)
Azim Khan8d686bf2018-07-04 23:29:46 +0100817 if typ == 'int' and not re.match(r'(\d+|0x[0-9a-f]+)$',
818 val, re.I):
Azim Khan599cd242017-07-06 17:34:27 +0100819 typ = 'exp'
820 if val not in unique_expressions:
821 unique_expressions.append(val)
Azim Khan040b6a22018-06-28 16:49:13 +0100822 # exp_id can be derived from len(). But for
823 # readability and consistency with case of existing
824 # let's use index().
Azim Khan599cd242017-07-06 17:34:27 +0100825 exp_id = unique_expressions.index(val)
826 expression_code += gen_expression_check(exp_id, val)
827 val = exp_id
828 else:
829 val = unique_expressions.index(val)
830 out_data_f.write(':' + typ + ':' + str(val))
831 out_data_f.write('\n')
832 return expression_code
833
834
Azim Khanb31aa442018-07-03 11:57:54 +0100835def gen_suite_dep_checks(suite_dependencies, dep_check_code, expression_code):
Azim Khan599cd242017-07-06 17:34:27 +0100836 """
Azim Khane3b26af2018-06-29 02:36:57 +0100837 Generates preprocessor checks for test suite dependencies.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100838
Azim Khanb31aa442018-07-03 11:57:54 +0100839 :param suite_dependencies: Test suite dependencies read from the
Azim Khan8d686bf2018-07-04 23:29:46 +0100840 .function file.
Azim Khanf0e42fb2017-08-02 14:47:13 +0100841 :param dep_check_code: Dependency check code
842 :param expression_code: Expression check code
Azim Khan040b6a22018-06-28 16:49:13 +0100843 :return: Dependency and expression code guarded by test suite
844 dependencies.
Azim Khan599cd242017-07-06 17:34:27 +0100845 """
Azim Khanb31aa442018-07-03 11:57:54 +0100846 if suite_dependencies:
847 preprocessor_check = gen_dependencies_one_line(suite_dependencies)
Azim Khan599cd242017-07-06 17:34:27 +0100848 dep_check_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100849{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100850{code}
Azim Khan599cd242017-07-06 17:34:27 +0100851#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100852'''.format(preprocessor_check=preprocessor_check, code=dep_check_code)
Azim Khan599cd242017-07-06 17:34:27 +0100853 expression_code = '''
Azim Khanb31aa442018-07-03 11:57:54 +0100854{preprocessor_check}
Azim Khan599cd242017-07-06 17:34:27 +0100855{code}
Azim Khan599cd242017-07-06 17:34:27 +0100856#endif
Azim Khanb31aa442018-07-03 11:57:54 +0100857'''.format(preprocessor_check=preprocessor_check, code=expression_code)
Azim Khan599cd242017-07-06 17:34:27 +0100858 return dep_check_code, expression_code
Azim Khan5e2ac1f2017-07-03 13:58:20 +0100859
860
Azim Khanb31aa442018-07-03 11:57:54 +0100861def gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100862 """
Azim Khane3b26af2018-06-29 02:36:57 +0100863 This function reads test case name, dependencies and test vectors
864 from the .data file. This information is correlated with the test
865 functions file for generating an intermediate data file replacing
866 the strings for test function names, dependencies and integer
867 constant expressions with identifiers. Mainly for optimising
868 space for on-target execution.
869 It also generates test case dependency check code and expression
870 evaluation code.
Mohammad Azim Khanb73159d2018-06-13 16:31:26 +0100871
Azim Khanf0e42fb2017-08-02 14:47:13 +0100872 :param data_f: Data file object
Azim Khan8d686bf2018-07-04 23:29:46 +0100873 :param out_data_f: Output intermediate data file
Azim Khan040b6a22018-06-28 16:49:13 +0100874 :param func_info: Dict keyed by function and with function id
875 and arguments info
Azim Khanb31aa442018-07-03 11:57:54 +0100876 :param suite_dependencies: Test suite dependencies
Azim Khanf0e42fb2017-08-02 14:47:13 +0100877 :return: Returns dependency and expression check code
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100878 """
Azim Khanb31aa442018-07-03 11:57:54 +0100879 unique_dependencies = []
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100880 unique_expressions = []
881 dep_check_code = ''
882 expression_code = ''
Azim Khanb31aa442018-07-03 11:57:54 +0100883 for test_name, function_name, test_dependencies, test_args in \
884 parse_test_data(data_f):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100885 out_data_f.write(test_name + '\n')
886
Azim Khanb31aa442018-07-03 11:57:54 +0100887 # Write dependencies
888 dep_check_code += write_dependencies(out_data_f, test_dependencies,
889 unique_dependencies)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100890
Azim Khan599cd242017-07-06 17:34:27 +0100891 # Write test function name
892 test_function_name = 'test_' + function_name
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100893 if test_function_name not in func_info:
Azim Khan040b6a22018-06-28 16:49:13 +0100894 raise GeneratorInputError("Function %s not found!" %
895 test_function_name)
Azim Khan599cd242017-07-06 17:34:27 +0100896 func_id, func_args = func_info[test_function_name]
897 out_data_f.write(str(func_id))
898
899 # Write parameters
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +0100900 if len(test_args) != len(func_args):
Azim Khan040b6a22018-06-28 16:49:13 +0100901 raise GeneratorInputError("Invalid number of arguments in test "
Azim Khanb31aa442018-07-03 11:57:54 +0100902 "%s. See function %s signature." %
903 (test_name, function_name))
Azim Khan040b6a22018-06-28 16:49:13 +0100904 expression_code += write_parameters(out_data_f, test_args, func_args,
905 unique_expressions)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100906
Azim Khan599cd242017-07-06 17:34:27 +0100907 # Write a newline as test case separator
908 out_data_f.write('\n')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100909
Azim Khanb31aa442018-07-03 11:57:54 +0100910 dep_check_code, expression_code = gen_suite_dep_checks(
911 suite_dependencies, dep_check_code, expression_code)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100912 return dep_check_code, expression_code
913
914
Azim Khanb31aa442018-07-03 11:57:54 +0100915def add_input_info(funcs_file, data_file, template_file,
916 c_file, snippets):
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100917 """
Azim Khanb31aa442018-07-03 11:57:54 +0100918 Add generator input info in snippets.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100919
Azim Khanf0e42fb2017-08-02 14:47:13 +0100920 :param funcs_file: Functions file object
921 :param data_file: Data file object
922 :param template_file: Template file object
Azim Khanf0e42fb2017-08-02 14:47:13 +0100923 :param c_file: Output C file object
Azim Khanb31aa442018-07-03 11:57:54 +0100924 :param snippets: Dictionary to contain code pieces to be
925 substituted in the template.
Mohammad Azim Khanfff49042017-03-28 01:48:31 +0100926 :return:
927 """
Azim Khanb31aa442018-07-03 11:57:54 +0100928 snippets['test_file'] = c_file
929 snippets['test_main_file'] = template_file
930 snippets['test_case_file'] = funcs_file
931 snippets['test_case_data_file'] = data_file
932
933
934def read_code_from_input_files(platform_file, helpers_file,
935 out_data_file, snippets):
936 """
937 Read code from input files and create substitutions for replacement
938 strings in the template file.
939
940 :param platform_file: Platform file object
941 :param helpers_file: Helper functions file object
942 :param out_data_file: Output intermediate data file object
943 :param snippets: Dictionary to contain code pieces to be
944 substituted in the template.
945 :return:
946 """
947 # Read helpers
948 with open(helpers_file, 'r') as help_f, open(platform_file, 'r') as \
949 platform_f:
950 snippets['test_common_helper_file'] = helpers_file
951 snippets['test_common_helpers'] = help_f.read()
952 snippets['test_platform_file'] = platform_file
953 snippets['platform_code'] = platform_f.read().replace(
954 'DATA_FILE', out_data_file.replace('\\', '\\\\')) # escape '\'
955
956
957def write_test_source_file(template_file, c_file, snippets):
958 """
959 Write output source file with generated source code.
960
961 :param template_file: Template file name
962 :param c_file: Output source file
963 :param snippets: Generated and code snippets
964 :return:
965 """
966 with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
Mohammad Azim Khand2d01122018-07-18 17:48:37 +0100967 for line_no, line in enumerate(template_f.readlines(), 1):
Azim Khanb31aa442018-07-03 11:57:54 +0100968 # Update line number. +1 as #line directive sets next line number
969 snippets['line_no'] = line_no + 1
970 code = line.format(**snippets)
971 c_f.write(code)
Azim Khanb31aa442018-07-03 11:57:54 +0100972
973
974def parse_function_file(funcs_file, snippets):
975 """
976 Parse function file and generate function dispatch code.
977
978 :param funcs_file: Functions file name
979 :param snippets: Dictionary to contain code pieces to be
980 substituted in the template.
981 :return:
982 """
983 with FileWrapper(funcs_file) as funcs_f:
984 suite_dependencies, dispatch_code, func_code, func_info = \
985 parse_functions(funcs_f)
986 snippets['functions_code'] = func_code
987 snippets['dispatch_code'] = dispatch_code
988 return suite_dependencies, func_info
989
990
991def generate_intermediate_data_file(data_file, out_data_file,
992 suite_dependencies, func_info, snippets):
993 """
994 Generates intermediate data file from input data file and
995 information read from functions file.
996
997 :param data_file: Data file name
998 :param out_data_file: Output/Intermediate data file
999 :param suite_dependencies: List of suite dependencies.
1000 :param func_info: Function info parsed from functions file.
1001 :param snippets: Dictionary to contain code pieces to be
1002 substituted in the template.
1003 :return:
1004 """
1005 with FileWrapper(data_file) as data_f, \
1006 open(out_data_file, 'w') as out_data_f:
1007 dep_check_code, expression_code = gen_from_test_data(
1008 data_f, out_data_f, func_info, suite_dependencies)
1009 snippets['dep_check_code'] = dep_check_code
1010 snippets['expression_code'] = expression_code
1011
1012
1013def generate_code(**input_info):
1014 """
1015 Generates C source code from test suite file, data file, common
1016 helpers file and platform file.
1017
1018 input_info expands to following parameters:
1019 funcs_file: Functions file object
1020 data_file: Data file object
1021 template_file: Template file object
1022 platform_file: Platform file object
1023 helpers_file: Helper functions file object
1024 suites_dir: Test suites dir
1025 c_file: Output C file object
1026 out_data_file: Output intermediate data file object
1027 :return:
1028 """
1029 funcs_file = input_info['funcs_file']
1030 data_file = input_info['data_file']
1031 template_file = input_info['template_file']
1032 platform_file = input_info['platform_file']
1033 helpers_file = input_info['helpers_file']
1034 suites_dir = input_info['suites_dir']
1035 c_file = input_info['c_file']
1036 out_data_file = input_info['out_data_file']
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001037 for name, path in [('Functions file', funcs_file),
1038 ('Data file', data_file),
1039 ('Template file', template_file),
1040 ('Platform file', platform_file),
Azim Khane3b26af2018-06-29 02:36:57 +01001041 ('Helpers code file', helpers_file),
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001042 ('Suites dir', suites_dir)]:
1043 if not os.path.exists(path):
1044 raise IOError("ERROR: %s [%s] not found!" % (name, path))
1045
Azim Khanb31aa442018-07-03 11:57:54 +01001046 snippets = {'generator_script': os.path.basename(__file__)}
1047 read_code_from_input_files(platform_file, helpers_file,
1048 out_data_file, snippets)
1049 add_input_info(funcs_file, data_file, template_file,
1050 c_file, snippets)
1051 suite_dependencies, func_info = parse_function_file(funcs_file, snippets)
1052 generate_intermediate_data_file(data_file, out_data_file,
1053 suite_dependencies, func_info, snippets)
1054 write_test_source_file(template_file, c_file, snippets)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001055
1056
Azim Khan8d686bf2018-07-04 23:29:46 +01001057def main():
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001058 """
1059 Command line parser.
1060
1061 :return:
1062 """
Azim Khan040b6a22018-06-28 16:49:13 +01001063 parser = argparse.ArgumentParser(
Azim Khane3b26af2018-06-29 02:36:57 +01001064 description='Dynamically generate test suite code.')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001065
1066 parser.add_argument("-f", "--functions-file",
1067 dest="funcs_file",
1068 help="Functions file",
Azim Khane3b26af2018-06-29 02:36:57 +01001069 metavar="FUNCTIONS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001070 required=True)
1071
1072 parser.add_argument("-d", "--data-file",
1073 dest="data_file",
1074 help="Data file",
Azim Khane3b26af2018-06-29 02:36:57 +01001075 metavar="DATA_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001076 required=True)
1077
1078 parser.add_argument("-t", "--template-file",
1079 dest="template_file",
1080 help="Template file",
Azim Khane3b26af2018-06-29 02:36:57 +01001081 metavar="TEMPLATE_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001082 required=True)
1083
1084 parser.add_argument("-s", "--suites-dir",
1085 dest="suites_dir",
1086 help="Suites dir",
Azim Khane3b26af2018-06-29 02:36:57 +01001087 metavar="SUITES_DIR",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001088 required=True)
1089
Azim Khane3b26af2018-06-29 02:36:57 +01001090 parser.add_argument("--helpers-file",
1091 dest="helpers_file",
1092 help="Helpers file",
1093 metavar="HELPERS_FILE",
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001094 required=True)
1095
1096 parser.add_argument("-p", "--platform-file",
1097 dest="platform_file",
1098 help="Platform code file",
1099 metavar="PLATFORM_FILE",
1100 required=True)
1101
1102 parser.add_argument("-o", "--out-dir",
1103 dest="out_dir",
1104 help="Dir where generated code and scripts are copied",
1105 metavar="OUT_DIR",
1106 required=True)
1107
1108 args = parser.parse_args()
1109
1110 data_file_name = os.path.basename(args.data_file)
1111 data_name = os.path.splitext(data_file_name)[0]
1112
1113 out_c_file = os.path.join(args.out_dir, data_name + '.c')
Mohammad Azim Khan00c4b092018-06-28 13:10:19 +01001114 out_data_file = os.path.join(args.out_dir, data_name + '.datax')
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001115
1116 out_c_file_dir = os.path.dirname(out_c_file)
1117 out_data_file_dir = os.path.dirname(out_data_file)
Azim Khanb31aa442018-07-03 11:57:54 +01001118 for directory in [out_c_file_dir, out_data_file_dir]:
1119 if not os.path.exists(directory):
1120 os.makedirs(directory)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001121
Azim Khanb31aa442018-07-03 11:57:54 +01001122 generate_code(funcs_file=args.funcs_file, data_file=args.data_file,
1123 template_file=args.template_file,
1124 platform_file=args.platform_file,
1125 helpers_file=args.helpers_file, suites_dir=args.suites_dir,
1126 c_file=out_c_file, out_data_file=out_data_file)
Mohammad Azim Khanfff49042017-03-28 01:48:31 +01001127
1128
1129if __name__ == "__main__":
Mohammad Azim Khan3b06f222018-06-26 14:35:25 +01001130 try:
Azim Khan8d686bf2018-07-04 23:29:46 +01001131 main()
Azim Khanb31aa442018-07-03 11:57:54 +01001132 except GeneratorInputError as err:
Mohammad Azim Khan440d8732018-07-18 12:50:49 +01001133 sys.exit("%s: input error: %s" %
1134 (os.path.basename(sys.argv[0]), str(err)))