generate_test_code.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. #!/usr/bin/env python3
  2. # Test suites code generator.
  3. #
  4. # Copyright The Mbed TLS Contributors
  5. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. #
  7. # This file is provided under the Apache License 2.0, or the
  8. # GNU General Public License v2.0 or later.
  9. #
  10. # **********
  11. # Apache License 2.0:
  12. #
  13. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  14. # not use this file except in compliance with the License.
  15. # You may obtain a copy of the License at
  16. #
  17. # http://www.apache.org/licenses/LICENSE-2.0
  18. #
  19. # Unless required by applicable law or agreed to in writing, software
  20. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. # See the License for the specific language governing permissions and
  23. # limitations under the License.
  24. #
  25. # **********
  26. #
  27. # **********
  28. # GNU General Public License v2.0 or later:
  29. #
  30. # This program is free software; you can redistribute it and/or modify
  31. # it under the terms of the GNU General Public License as published by
  32. # the Free Software Foundation; either version 2 of the License, or
  33. # (at your option) any later version.
  34. #
  35. # This program is distributed in the hope that it will be useful,
  36. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. # GNU General Public License for more details.
  39. #
  40. # You should have received a copy of the GNU General Public License along
  41. # with this program; if not, write to the Free Software Foundation, Inc.,
  42. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  43. #
  44. # **********
  45. """
  46. This script is a key part of Mbed TLS test suites framework. For
  47. understanding the script it is important to understand the
  48. framework. This doc string contains a summary of the framework
  49. and explains the function of this script.
  50. Mbed TLS test suites:
  51. =====================
  52. Scope:
  53. ------
  54. The test suites focus on unit testing the crypto primitives and also
  55. include x509 parser tests. Tests can be added to test any Mbed TLS
  56. module. However, the framework is not capable of testing SSL
  57. protocol, since that requires full stack execution and that is best
  58. tested as part of the system test.
  59. Test case definition:
  60. ---------------------
  61. Tests are defined in a test_suite_<module>[.<optional sub module>].data
  62. file. A test definition contains:
  63. test name
  64. optional build macro dependencies
  65. test function
  66. test parameters
  67. Test dependencies are build macros that can be specified to indicate
  68. the build config in which the test is valid. For example if a test
  69. depends on a feature that is only enabled by defining a macro. Then
  70. that macro should be specified as a dependency of the test.
  71. Test function is the function that implements the test steps. This
  72. function is specified for different tests that perform same steps
  73. with different parameters.
  74. Test parameters are specified in string form separated by ':'.
  75. Parameters can be of type string, binary data specified as hex
  76. string and integer constants specified as integer, macro or
  77. as an expression. Following is an example test definition:
  78. AES 128 GCM Encrypt and decrypt 8 bytes
  79. depends_on:MBEDTLS_AES_C:MBEDTLS_GCM_C
  80. enc_dec_buf:MBEDTLS_CIPHER_AES_128_GCM:"AES-128-GCM":128:8:-1
  81. Test functions:
  82. ---------------
  83. Test functions are coded in C in test_suite_<module>.function files.
  84. Functions file is itself not compilable and contains special
  85. format patterns to specify test suite dependencies, start and end
  86. of functions and function dependencies. Check any existing functions
  87. file for example.
  88. Execution:
  89. ----------
  90. Tests are executed in 3 steps:
  91. - Generating test_suite_<module>[.<optional sub module>].c file
  92. for each corresponding .data file.
  93. - Building each source file into executables.
  94. - Running each executable and printing report.
  95. Generating C test source requires more than just the test functions.
  96. Following extras are required:
  97. - Process main()
  98. - Reading .data file and dispatching test cases.
  99. - Platform specific test case execution
  100. - Dependency checking
  101. - Integer expression evaluation
  102. - Test function dispatch
  103. Build dependencies and integer expressions (in the test parameters)
  104. are specified as strings in the .data file. Their run time value is
  105. not known at the generation stage. Hence, they need to be translated
  106. into run time evaluations. This script generates the run time checks
  107. for dependencies and integer expressions.
  108. Similarly, function names have to be translated into function calls.
  109. This script also generates code for function dispatch.
  110. The extra code mentioned here is either generated by this script
  111. or it comes from the input files: helpers file, platform file and
  112. the template file.
  113. Helper file:
  114. ------------
  115. Helpers file contains common helper/utility functions and data.
  116. Platform file:
  117. --------------
  118. Platform file contains platform specific setup code and test case
  119. dispatch code. For example, host_test.function reads test data
  120. file from host's file system and dispatches tests.
  121. In case of on-target target_test.function tests are not dispatched
  122. on target. Target code is kept minimum and only test functions are
  123. dispatched. Test case dispatch is done on the host using tools like
  124. Greentea.
  125. Template file:
  126. ---------
  127. Template file for example main_test.function is a template C file in
  128. which generated code and code from input files is substituted to
  129. generate a compilable C file. It also contains skeleton functions for
  130. dependency checks, expression evaluation and function dispatch. These
  131. functions are populated with checks and return codes by this script.
  132. Template file contains "replacement" fields that are formatted
  133. strings processed by Python string.Template.substitute() method.
  134. This script:
  135. ============
  136. Core function of this script is to fill the template file with
  137. code that is generated or read from helpers and platform files.
  138. This script replaces following fields in the template and generates
  139. the test source file:
  140. $test_common_helpers <-- All common code from helpers.function
  141. is substituted here.
  142. $functions_code <-- Test functions are substituted here
  143. from the input test_suit_xyz.function
  144. file. C preprocessor checks are generated
  145. for the build dependencies specified
  146. in the input file. This script also
  147. generates wrappers for the test
  148. functions with code to expand the
  149. string parameters read from the data
  150. file.
  151. $expression_code <-- This script enumerates the
  152. expressions in the .data file and
  153. generates code to handle enumerated
  154. expression Ids and return the values.
  155. $dep_check_code <-- This script enumerates all
  156. build dependencies and generate
  157. code to handle enumerated build
  158. dependency Id and return status: if
  159. the dependency is defined or not.
  160. $dispatch_code <-- This script enumerates the functions
  161. specified in the input test data file
  162. and generates the initializer for the
  163. function table in the template
  164. file.
  165. $platform_code <-- Platform specific setup and test
  166. dispatch code.
  167. """
  168. import io
  169. import os
  170. import re
  171. import sys
  172. import string
  173. import argparse
  174. BEGIN_HEADER_REGEX = r'/\*\s*BEGIN_HEADER\s*\*/'
  175. END_HEADER_REGEX = r'/\*\s*END_HEADER\s*\*/'
  176. BEGIN_SUITE_HELPERS_REGEX = r'/\*\s*BEGIN_SUITE_HELPERS\s*\*/'
  177. END_SUITE_HELPERS_REGEX = r'/\*\s*END_SUITE_HELPERS\s*\*/'
  178. BEGIN_DEP_REGEX = r'BEGIN_DEPENDENCIES'
  179. END_DEP_REGEX = r'END_DEPENDENCIES'
  180. BEGIN_CASE_REGEX = r'/\*\s*BEGIN_CASE\s*(?P<depends_on>.*?)\s*\*/'
  181. END_CASE_REGEX = r'/\*\s*END_CASE\s*\*/'
  182. DEPENDENCY_REGEX = r'depends_on:(?P<dependencies>.*)'
  183. C_IDENTIFIER_REGEX = r'!?[a-z_][a-z0-9_]*'
  184. CONDITION_OPERATOR_REGEX = r'[!=]=|[<>]=?'
  185. # forbid 0ddd which might be accidentally octal or accidentally decimal
  186. CONDITION_VALUE_REGEX = r'[-+]?(0x[0-9a-f]+|0|[1-9][0-9]*)'
  187. CONDITION_REGEX = r'({})(?:\s*({})\s*({}))?$'.format(C_IDENTIFIER_REGEX,
  188. CONDITION_OPERATOR_REGEX,
  189. CONDITION_VALUE_REGEX)
  190. TEST_FUNCTION_VALIDATION_REGEX = r'\s*void\s+(?P<func_name>\w+)\s*\('
  191. INT_CHECK_REGEX = r'int\s+.*'
  192. CHAR_CHECK_REGEX = r'char\s*\*\s*.*'
  193. DATA_T_CHECK_REGEX = r'data_t\s*\*\s*.*'
  194. FUNCTION_ARG_LIST_END_REGEX = r'.*\)'
  195. EXIT_LABEL_REGEX = r'^exit:'
  196. class GeneratorInputError(Exception):
  197. """
  198. Exception to indicate error in the input files to this script.
  199. This includes missing patterns, test function names and other
  200. parsing errors.
  201. """
  202. pass
  203. class FileWrapper(io.FileIO):
  204. """
  205. This class extends built-in io.FileIO class with attribute line_no,
  206. that indicates line number for the line that is read.
  207. """
  208. def __init__(self, file_name):
  209. """
  210. Instantiate the base class and initialize the line number to 0.
  211. :param file_name: File path to open.
  212. """
  213. super(FileWrapper, self).__init__(file_name, 'r')
  214. self._line_no = 0
  215. def next(self):
  216. """
  217. Python 2 iterator method. This method overrides base class's
  218. next method and extends the next method to count the line
  219. numbers as each line is read.
  220. It works for both Python 2 and Python 3 by checking iterator
  221. method name in the base iterator object.
  222. :return: Line read from file.
  223. """
  224. parent = super(FileWrapper, self)
  225. if hasattr(parent, '__next__'):
  226. line = parent.__next__() # Python 3
  227. else:
  228. line = parent.next() # Python 2 # pylint: disable=no-member
  229. if line is not None:
  230. self._line_no += 1
  231. # Convert byte array to string with correct encoding and
  232. # strip any whitespaces added in the decoding process.
  233. return line.decode(sys.getdefaultencoding()).rstrip() + '\n'
  234. return None
  235. # Python 3 iterator method
  236. __next__ = next
  237. def get_line_no(self):
  238. """
  239. Gives current line number.
  240. """
  241. return self._line_no
  242. line_no = property(get_line_no)
  243. def split_dep(dep):
  244. """
  245. Split NOT character '!' from dependency. Used by gen_dependencies()
  246. :param dep: Dependency list
  247. :return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
  248. MACRO.
  249. """
  250. return ('!', dep[1:]) if dep[0] == '!' else ('', dep)
  251. def gen_dependencies(dependencies):
  252. """
  253. Test suite data and functions specifies compile time dependencies.
  254. This function generates C preprocessor code from the input
  255. dependency list. Caller uses the generated preprocessor code to
  256. wrap dependent code.
  257. A dependency in the input list can have a leading '!' character
  258. to negate a condition. '!' is separated from the dependency using
  259. function split_dep() and proper preprocessor check is generated
  260. accordingly.
  261. :param dependencies: List of dependencies.
  262. :return: if defined and endif code with macro annotations for
  263. readability.
  264. """
  265. dep_start = ''.join(['#if %sdefined(%s)\n' % (x, y) for x, y in
  266. map(split_dep, dependencies)])
  267. dep_end = ''.join(['#endif /* %s */\n' %
  268. x for x in reversed(dependencies)])
  269. return dep_start, dep_end
  270. def gen_dependencies_one_line(dependencies):
  271. """
  272. Similar to gen_dependencies() but generates dependency checks in one line.
  273. Useful for generating code with #else block.
  274. :param dependencies: List of dependencies.
  275. :return: Preprocessor check code
  276. """
  277. defines = '#if ' if dependencies else ''
  278. defines += ' && '.join(['%sdefined(%s)' % (x, y) for x, y in map(
  279. split_dep, dependencies)])
  280. return defines
  281. def gen_function_wrapper(name, local_vars, args_dispatch):
  282. """
  283. Creates test function wrapper code. A wrapper has the code to
  284. unpack parameters from parameters[] array.
  285. :param name: Test function name
  286. :param local_vars: Local variables declaration code
  287. :param args_dispatch: List of dispatch arguments.
  288. Ex: ['(char *)params[0]', '*((int *)params[1])']
  289. :return: Test function wrapper.
  290. """
  291. # Then create the wrapper
  292. wrapper = '''
  293. void {name}_wrapper( void ** params )
  294. {{
  295. {unused_params}{locals}
  296. {name}( {args} );
  297. }}
  298. '''.format(name=name,
  299. unused_params='' if args_dispatch else ' (void)params;\n',
  300. args=', '.join(args_dispatch),
  301. locals=local_vars)
  302. return wrapper
  303. def gen_dispatch(name, dependencies):
  304. """
  305. Test suite code template main_test.function defines a C function
  306. array to contain test case functions. This function generates an
  307. initializer entry for a function in that array. The entry is
  308. composed of a compile time check for the test function
  309. dependencies. At compile time the test function is assigned when
  310. dependencies are met, else NULL is assigned.
  311. :param name: Test function name
  312. :param dependencies: List of dependencies
  313. :return: Dispatch code.
  314. """
  315. if dependencies:
  316. preprocessor_check = gen_dependencies_one_line(dependencies)
  317. dispatch_code = '''
  318. {preprocessor_check}
  319. {name}_wrapper,
  320. #else
  321. NULL,
  322. #endif
  323. '''.format(preprocessor_check=preprocessor_check, name=name)
  324. else:
  325. dispatch_code = '''
  326. {name}_wrapper,
  327. '''.format(name=name)
  328. return dispatch_code
  329. def parse_until_pattern(funcs_f, end_regex):
  330. """
  331. Matches pattern end_regex to the lines read from the file object.
  332. Returns the lines read until end pattern is matched.
  333. :param funcs_f: file object for .function file
  334. :param end_regex: Pattern to stop parsing
  335. :return: Lines read before the end pattern
  336. """
  337. headers = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
  338. for line in funcs_f:
  339. if re.search(end_regex, line):
  340. break
  341. headers += line
  342. else:
  343. raise GeneratorInputError("file: %s - end pattern [%s] not found!" %
  344. (funcs_f.name, end_regex))
  345. return headers
  346. def validate_dependency(dependency):
  347. """
  348. Validates a C macro and raises GeneratorInputError on invalid input.
  349. :param dependency: Input macro dependency
  350. :return: input dependency stripped of leading & trailing white spaces.
  351. """
  352. dependency = dependency.strip()
  353. if not re.match(CONDITION_REGEX, dependency, re.I):
  354. raise GeneratorInputError('Invalid dependency %s' % dependency)
  355. return dependency
  356. def parse_dependencies(inp_str):
  357. """
  358. Parses dependencies out of inp_str, validates them and returns a
  359. list of macros.
  360. :param inp_str: Input string with macros delimited by ':'.
  361. :return: list of dependencies
  362. """
  363. dependencies = list(map(validate_dependency, inp_str.split(':')))
  364. return dependencies
  365. def parse_suite_dependencies(funcs_f):
  366. """
  367. Parses test suite dependencies specified at the top of a
  368. .function file, that starts with pattern BEGIN_DEPENDENCIES
  369. and end with END_DEPENDENCIES. Dependencies are specified
  370. after pattern 'depends_on:' and are delimited by ':'.
  371. :param funcs_f: file object for .function file
  372. :return: List of test suite dependencies.
  373. """
  374. dependencies = []
  375. for line in funcs_f:
  376. match = re.search(DEPENDENCY_REGEX, line.strip())
  377. if match:
  378. try:
  379. dependencies = parse_dependencies(match.group('dependencies'))
  380. except GeneratorInputError as error:
  381. raise GeneratorInputError(
  382. str(error) + " - %s:%d" % (funcs_f.name, funcs_f.line_no))
  383. if re.search(END_DEP_REGEX, line):
  384. break
  385. else:
  386. raise GeneratorInputError("file: %s - end dependency pattern [%s]"
  387. " not found!" % (funcs_f.name,
  388. END_DEP_REGEX))
  389. return dependencies
  390. def parse_function_dependencies(line):
  391. """
  392. Parses function dependencies, that are in the same line as
  393. comment BEGIN_CASE. Dependencies are specified after pattern
  394. 'depends_on:' and are delimited by ':'.
  395. :param line: Line from .function file that has dependencies.
  396. :return: List of dependencies.
  397. """
  398. dependencies = []
  399. match = re.search(BEGIN_CASE_REGEX, line)
  400. dep_str = match.group('depends_on')
  401. if dep_str:
  402. match = re.search(DEPENDENCY_REGEX, dep_str)
  403. if match:
  404. dependencies += parse_dependencies(match.group('dependencies'))
  405. return dependencies
  406. def parse_function_arguments(line):
  407. """
  408. Parses test function signature for validation and generates
  409. a dispatch wrapper function that translates input test vectors
  410. read from the data file into test function arguments.
  411. :param line: Line from .function file that has a function
  412. signature.
  413. :return: argument list, local variables for
  414. wrapper function and argument dispatch code.
  415. """
  416. args = []
  417. local_vars = ''
  418. args_dispatch = []
  419. arg_idx = 0
  420. # Remove characters before arguments
  421. line = line[line.find('(') + 1:]
  422. # Process arguments, ex: <type> arg1, <type> arg2 )
  423. # This script assumes that the argument list is terminated by ')'
  424. # i.e. the test functions will not have a function pointer
  425. # argument.
  426. for arg in line[:line.find(')')].split(','):
  427. arg = arg.strip()
  428. if arg == '':
  429. continue
  430. if re.search(INT_CHECK_REGEX, arg.strip()):
  431. args.append('int')
  432. args_dispatch.append('*( (int *) params[%d] )' % arg_idx)
  433. elif re.search(CHAR_CHECK_REGEX, arg.strip()):
  434. args.append('char*')
  435. args_dispatch.append('(char *) params[%d]' % arg_idx)
  436. elif re.search(DATA_T_CHECK_REGEX, arg.strip()):
  437. args.append('hex')
  438. # create a structure
  439. pointer_initializer = '(uint8_t *) params[%d]' % arg_idx
  440. len_initializer = '*( (uint32_t *) params[%d] )' % (arg_idx+1)
  441. local_vars += """ data_t data%d = {%s, %s};
  442. """ % (arg_idx, pointer_initializer, len_initializer)
  443. args_dispatch.append('&data%d' % arg_idx)
  444. arg_idx += 1
  445. else:
  446. raise ValueError("Test function arguments can only be 'int', "
  447. "'char *' or 'data_t'\n%s" % line)
  448. arg_idx += 1
  449. return args, local_vars, args_dispatch
  450. def generate_function_code(name, code, local_vars, args_dispatch,
  451. dependencies):
  452. """
  453. Generate function code with preprocessor checks and parameter dispatch
  454. wrapper.
  455. :param name: Function name
  456. :param code: Function code
  457. :param local_vars: Local variables for function wrapper
  458. :param args_dispatch: Argument dispatch code
  459. :param dependencies: Preprocessor dependencies list
  460. :return: Final function code
  461. """
  462. # Add exit label if not present
  463. if code.find('exit:') == -1:
  464. split_code = code.rsplit('}', 1)
  465. if len(split_code) == 2:
  466. code = """exit:
  467. ;
  468. }""".join(split_code)
  469. code += gen_function_wrapper(name, local_vars, args_dispatch)
  470. preprocessor_check_start, preprocessor_check_end = \
  471. gen_dependencies(dependencies)
  472. return preprocessor_check_start + code + preprocessor_check_end
  473. def parse_function_code(funcs_f, dependencies, suite_dependencies):
  474. """
  475. Parses out a function from function file object and generates
  476. function and dispatch code.
  477. :param funcs_f: file object of the functions file.
  478. :param dependencies: List of dependencies
  479. :param suite_dependencies: List of test suite dependencies
  480. :return: Function name, arguments, function code and dispatch code.
  481. """
  482. line_directive = '#line %d "%s"\n' % (funcs_f.line_no + 1, funcs_f.name)
  483. code = ''
  484. has_exit_label = False
  485. for line in funcs_f:
  486. # Check function signature. Function signature may be split
  487. # across multiple lines. Here we try to find the start of
  488. # arguments list, then remove '\n's and apply the regex to
  489. # detect function start.
  490. up_to_arg_list_start = code + line[:line.find('(') + 1]
  491. match = re.match(TEST_FUNCTION_VALIDATION_REGEX,
  492. up_to_arg_list_start.replace('\n', ' '), re.I)
  493. if match:
  494. # check if we have full signature i.e. split in more lines
  495. name = match.group('func_name')
  496. if not re.match(FUNCTION_ARG_LIST_END_REGEX, line):
  497. for lin in funcs_f:
  498. line += lin
  499. if re.search(FUNCTION_ARG_LIST_END_REGEX, line):
  500. break
  501. args, local_vars, args_dispatch = parse_function_arguments(
  502. line)
  503. code += line
  504. break
  505. code += line
  506. else:
  507. raise GeneratorInputError("file: %s - Test functions not found!" %
  508. funcs_f.name)
  509. # Prefix test function name with 'test_'
  510. code = code.replace(name, 'test_' + name, 1)
  511. name = 'test_' + name
  512. for line in funcs_f:
  513. if re.search(END_CASE_REGEX, line):
  514. break
  515. if not has_exit_label:
  516. has_exit_label = \
  517. re.search(EXIT_LABEL_REGEX, line.strip()) is not None
  518. code += line
  519. else:
  520. raise GeneratorInputError("file: %s - end case pattern [%s] not "
  521. "found!" % (funcs_f.name, END_CASE_REGEX))
  522. code = line_directive + code
  523. code = generate_function_code(name, code, local_vars, args_dispatch,
  524. dependencies)
  525. dispatch_code = gen_dispatch(name, suite_dependencies + dependencies)
  526. return (name, args, code, dispatch_code)
  527. def parse_functions(funcs_f):
  528. """
  529. Parses a test_suite_xxx.function file and returns information
  530. for generating a C source file for the test suite.
  531. :param funcs_f: file object of the functions file.
  532. :return: List of test suite dependencies, test function dispatch
  533. code, function code and a dict with function identifiers
  534. and arguments info.
  535. """
  536. suite_helpers = ''
  537. suite_dependencies = []
  538. suite_functions = ''
  539. func_info = {}
  540. function_idx = 0
  541. dispatch_code = ''
  542. for line in funcs_f:
  543. if re.search(BEGIN_HEADER_REGEX, line):
  544. suite_helpers += parse_until_pattern(funcs_f, END_HEADER_REGEX)
  545. elif re.search(BEGIN_SUITE_HELPERS_REGEX, line):
  546. suite_helpers += parse_until_pattern(funcs_f,
  547. END_SUITE_HELPERS_REGEX)
  548. elif re.search(BEGIN_DEP_REGEX, line):
  549. suite_dependencies += parse_suite_dependencies(funcs_f)
  550. elif re.search(BEGIN_CASE_REGEX, line):
  551. try:
  552. dependencies = parse_function_dependencies(line)
  553. except GeneratorInputError as error:
  554. raise GeneratorInputError(
  555. "%s:%d: %s" % (funcs_f.name, funcs_f.line_no,
  556. str(error)))
  557. func_name, args, func_code, func_dispatch =\
  558. parse_function_code(funcs_f, dependencies, suite_dependencies)
  559. suite_functions += func_code
  560. # Generate dispatch code and enumeration info
  561. if func_name in func_info:
  562. raise GeneratorInputError(
  563. "file: %s - function %s re-declared at line %d" %
  564. (funcs_f.name, func_name, funcs_f.line_no))
  565. func_info[func_name] = (function_idx, args)
  566. dispatch_code += '/* Function Id: %d */\n' % function_idx
  567. dispatch_code += func_dispatch
  568. function_idx += 1
  569. func_code = (suite_helpers +
  570. suite_functions).join(gen_dependencies(suite_dependencies))
  571. return suite_dependencies, dispatch_code, func_code, func_info
  572. def escaped_split(inp_str, split_char):
  573. """
  574. Split inp_str on character split_char but ignore if escaped.
  575. Since, return value is used to write back to the intermediate
  576. data file, any escape characters in the input are retained in the
  577. output.
  578. :param inp_str: String to split
  579. :param split_char: Split character
  580. :return: List of splits
  581. """
  582. if len(split_char) > 1:
  583. raise ValueError('Expected split character. Found string!')
  584. out = re.sub(r'(\\.)|' + split_char,
  585. lambda m: m.group(1) or '\n', inp_str,
  586. len(inp_str)).split('\n')
  587. out = [x for x in out if x]
  588. return out
  589. def parse_test_data(data_f):
  590. """
  591. Parses .data file for each test case name, test function name,
  592. test dependencies and test arguments. This information is
  593. correlated with the test functions file for generating an
  594. intermediate data file replacing the strings for test function
  595. names, dependencies and integer constant expressions with
  596. identifiers. Mainly for optimising space for on-target
  597. execution.
  598. :param data_f: file object of the data file.
  599. :return: Generator that yields test name, function name,
  600. dependency list and function argument list.
  601. """
  602. __state_read_name = 0
  603. __state_read_args = 1
  604. state = __state_read_name
  605. dependencies = []
  606. name = ''
  607. for line in data_f:
  608. line = line.strip()
  609. # Skip comments
  610. if line.startswith('#'):
  611. continue
  612. # Blank line indicates end of test
  613. if not line:
  614. if state == __state_read_args:
  615. raise GeneratorInputError("[%s:%d] Newline before arguments. "
  616. "Test function and arguments "
  617. "missing for %s" %
  618. (data_f.name, data_f.line_no, name))
  619. continue
  620. if state == __state_read_name:
  621. # Read test name
  622. name = line
  623. state = __state_read_args
  624. elif state == __state_read_args:
  625. # Check dependencies
  626. match = re.search(DEPENDENCY_REGEX, line)
  627. if match:
  628. try:
  629. dependencies = parse_dependencies(
  630. match.group('dependencies'))
  631. except GeneratorInputError as error:
  632. raise GeneratorInputError(
  633. str(error) + " - %s:%d" %
  634. (data_f.name, data_f.line_no))
  635. else:
  636. # Read test vectors
  637. parts = escaped_split(line, ':')
  638. test_function = parts[0]
  639. args = parts[1:]
  640. yield name, test_function, dependencies, args
  641. dependencies = []
  642. state = __state_read_name
  643. if state == __state_read_args:
  644. raise GeneratorInputError("[%s:%d] Newline before arguments. "
  645. "Test function and arguments missing for "
  646. "%s" % (data_f.name, data_f.line_no, name))
  647. def gen_dep_check(dep_id, dep):
  648. """
  649. Generate code for checking dependency with the associated
  650. identifier.
  651. :param dep_id: Dependency identifier
  652. :param dep: Dependency macro
  653. :return: Dependency check code
  654. """
  655. if dep_id < 0:
  656. raise GeneratorInputError("Dependency Id should be a positive "
  657. "integer.")
  658. _not, dep = ('!', dep[1:]) if dep[0] == '!' else ('', dep)
  659. if not dep:
  660. raise GeneratorInputError("Dependency should not be an empty string.")
  661. dependency = re.match(CONDITION_REGEX, dep, re.I)
  662. if not dependency:
  663. raise GeneratorInputError('Invalid dependency %s' % dep)
  664. _defined = '' if dependency.group(2) else 'defined'
  665. _cond = dependency.group(2) if dependency.group(2) else ''
  666. _value = dependency.group(3) if dependency.group(3) else ''
  667. dep_check = '''
  668. case {id}:
  669. {{
  670. #if {_not}{_defined}({macro}{_cond}{_value})
  671. ret = DEPENDENCY_SUPPORTED;
  672. #else
  673. ret = DEPENDENCY_NOT_SUPPORTED;
  674. #endif
  675. }}
  676. break;'''.format(_not=_not, _defined=_defined,
  677. macro=dependency.group(1), id=dep_id,
  678. _cond=_cond, _value=_value)
  679. return dep_check
  680. def gen_expression_check(exp_id, exp):
  681. """
  682. Generates code for evaluating an integer expression using
  683. associated expression Id.
  684. :param exp_id: Expression Identifier
  685. :param exp: Expression/Macro
  686. :return: Expression check code
  687. """
  688. if exp_id < 0:
  689. raise GeneratorInputError("Expression Id should be a positive "
  690. "integer.")
  691. if not exp:
  692. raise GeneratorInputError("Expression should not be an empty string.")
  693. exp_code = '''
  694. case {exp_id}:
  695. {{
  696. *out_value = {expression};
  697. }}
  698. break;'''.format(exp_id=exp_id, expression=exp)
  699. return exp_code
  700. def write_dependencies(out_data_f, test_dependencies, unique_dependencies):
  701. """
  702. Write dependencies to intermediate test data file, replacing
  703. the string form with identifiers. Also, generates dependency
  704. check code.
  705. :param out_data_f: Output intermediate data file
  706. :param test_dependencies: Dependencies
  707. :param unique_dependencies: Mutable list to track unique dependencies
  708. that are global to this re-entrant function.
  709. :return: returns dependency check code.
  710. """
  711. dep_check_code = ''
  712. if test_dependencies:
  713. out_data_f.write('depends_on')
  714. for dep in test_dependencies:
  715. if dep not in unique_dependencies:
  716. unique_dependencies.append(dep)
  717. dep_id = unique_dependencies.index(dep)
  718. dep_check_code += gen_dep_check(dep_id, dep)
  719. else:
  720. dep_id = unique_dependencies.index(dep)
  721. out_data_f.write(':' + str(dep_id))
  722. out_data_f.write('\n')
  723. return dep_check_code
  724. def write_parameters(out_data_f, test_args, func_args, unique_expressions):
  725. """
  726. Writes test parameters to the intermediate data file, replacing
  727. the string form with identifiers. Also, generates expression
  728. check code.
  729. :param out_data_f: Output intermediate data file
  730. :param test_args: Test parameters
  731. :param func_args: Function arguments
  732. :param unique_expressions: Mutable list to track unique
  733. expressions that are global to this re-entrant function.
  734. :return: Returns expression check code.
  735. """
  736. expression_code = ''
  737. for i, _ in enumerate(test_args):
  738. typ = func_args[i]
  739. val = test_args[i]
  740. # check if val is a non literal int val (i.e. an expression)
  741. if typ == 'int' and not re.match(r'(\d+|0x[0-9a-f]+)$',
  742. val, re.I):
  743. typ = 'exp'
  744. if val not in unique_expressions:
  745. unique_expressions.append(val)
  746. # exp_id can be derived from len(). But for
  747. # readability and consistency with case of existing
  748. # let's use index().
  749. exp_id = unique_expressions.index(val)
  750. expression_code += gen_expression_check(exp_id, val)
  751. val = exp_id
  752. else:
  753. val = unique_expressions.index(val)
  754. out_data_f.write(':' + typ + ':' + str(val))
  755. out_data_f.write('\n')
  756. return expression_code
  757. def gen_suite_dep_checks(suite_dependencies, dep_check_code, expression_code):
  758. """
  759. Generates preprocessor checks for test suite dependencies.
  760. :param suite_dependencies: Test suite dependencies read from the
  761. .function file.
  762. :param dep_check_code: Dependency check code
  763. :param expression_code: Expression check code
  764. :return: Dependency and expression code guarded by test suite
  765. dependencies.
  766. """
  767. if suite_dependencies:
  768. preprocessor_check = gen_dependencies_one_line(suite_dependencies)
  769. dep_check_code = '''
  770. {preprocessor_check}
  771. {code}
  772. #endif
  773. '''.format(preprocessor_check=preprocessor_check, code=dep_check_code)
  774. expression_code = '''
  775. {preprocessor_check}
  776. {code}
  777. #endif
  778. '''.format(preprocessor_check=preprocessor_check, code=expression_code)
  779. return dep_check_code, expression_code
  780. def gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies):
  781. """
  782. This function reads test case name, dependencies and test vectors
  783. from the .data file. This information is correlated with the test
  784. functions file for generating an intermediate data file replacing
  785. the strings for test function names, dependencies and integer
  786. constant expressions with identifiers. Mainly for optimising
  787. space for on-target execution.
  788. It also generates test case dependency check code and expression
  789. evaluation code.
  790. :param data_f: Data file object
  791. :param out_data_f: Output intermediate data file
  792. :param func_info: Dict keyed by function and with function id
  793. and arguments info
  794. :param suite_dependencies: Test suite dependencies
  795. :return: Returns dependency and expression check code
  796. """
  797. unique_dependencies = []
  798. unique_expressions = []
  799. dep_check_code = ''
  800. expression_code = ''
  801. for test_name, function_name, test_dependencies, test_args in \
  802. parse_test_data(data_f):
  803. out_data_f.write(test_name + '\n')
  804. # Write dependencies
  805. dep_check_code += write_dependencies(out_data_f, test_dependencies,
  806. unique_dependencies)
  807. # Write test function name
  808. test_function_name = 'test_' + function_name
  809. if test_function_name not in func_info:
  810. raise GeneratorInputError("Function %s not found!" %
  811. test_function_name)
  812. func_id, func_args = func_info[test_function_name]
  813. out_data_f.write(str(func_id))
  814. # Write parameters
  815. if len(test_args) != len(func_args):
  816. raise GeneratorInputError("Invalid number of arguments in test "
  817. "%s. See function %s signature." %
  818. (test_name, function_name))
  819. expression_code += write_parameters(out_data_f, test_args, func_args,
  820. unique_expressions)
  821. # Write a newline as test case separator
  822. out_data_f.write('\n')
  823. dep_check_code, expression_code = gen_suite_dep_checks(
  824. suite_dependencies, dep_check_code, expression_code)
  825. return dep_check_code, expression_code
  826. def add_input_info(funcs_file, data_file, template_file,
  827. c_file, snippets):
  828. """
  829. Add generator input info in snippets.
  830. :param funcs_file: Functions file object
  831. :param data_file: Data file object
  832. :param template_file: Template file object
  833. :param c_file: Output C file object
  834. :param snippets: Dictionary to contain code pieces to be
  835. substituted in the template.
  836. :return:
  837. """
  838. snippets['test_file'] = c_file
  839. snippets['test_main_file'] = template_file
  840. snippets['test_case_file'] = funcs_file
  841. snippets['test_case_data_file'] = data_file
  842. def read_code_from_input_files(platform_file, helpers_file,
  843. out_data_file, snippets):
  844. """
  845. Read code from input files and create substitutions for replacement
  846. strings in the template file.
  847. :param platform_file: Platform file object
  848. :param helpers_file: Helper functions file object
  849. :param out_data_file: Output intermediate data file object
  850. :param snippets: Dictionary to contain code pieces to be
  851. substituted in the template.
  852. :return:
  853. """
  854. # Read helpers
  855. with open(helpers_file, 'r') as help_f, open(platform_file, 'r') as \
  856. platform_f:
  857. snippets['test_common_helper_file'] = helpers_file
  858. snippets['test_common_helpers'] = help_f.read()
  859. snippets['test_platform_file'] = platform_file
  860. snippets['platform_code'] = platform_f.read().replace(
  861. 'DATA_FILE', out_data_file.replace('\\', '\\\\')) # escape '\'
  862. def write_test_source_file(template_file, c_file, snippets):
  863. """
  864. Write output source file with generated source code.
  865. :param template_file: Template file name
  866. :param c_file: Output source file
  867. :param snippets: Generated and code snippets
  868. :return:
  869. """
  870. with open(template_file, 'r') as template_f, open(c_file, 'w') as c_f:
  871. for line_no, line in enumerate(template_f.readlines(), 1):
  872. # Update line number. +1 as #line directive sets next line number
  873. snippets['line_no'] = line_no + 1
  874. code = string.Template(line).substitute(**snippets)
  875. c_f.write(code)
  876. def parse_function_file(funcs_file, snippets):
  877. """
  878. Parse function file and generate function dispatch code.
  879. :param funcs_file: Functions file name
  880. :param snippets: Dictionary to contain code pieces to be
  881. substituted in the template.
  882. :return:
  883. """
  884. with FileWrapper(funcs_file) as funcs_f:
  885. suite_dependencies, dispatch_code, func_code, func_info = \
  886. parse_functions(funcs_f)
  887. snippets['functions_code'] = func_code
  888. snippets['dispatch_code'] = dispatch_code
  889. return suite_dependencies, func_info
  890. def generate_intermediate_data_file(data_file, out_data_file,
  891. suite_dependencies, func_info, snippets):
  892. """
  893. Generates intermediate data file from input data file and
  894. information read from functions file.
  895. :param data_file: Data file name
  896. :param out_data_file: Output/Intermediate data file
  897. :param suite_dependencies: List of suite dependencies.
  898. :param func_info: Function info parsed from functions file.
  899. :param snippets: Dictionary to contain code pieces to be
  900. substituted in the template.
  901. :return:
  902. """
  903. with FileWrapper(data_file) as data_f, \
  904. open(out_data_file, 'w') as out_data_f:
  905. dep_check_code, expression_code = gen_from_test_data(
  906. data_f, out_data_f, func_info, suite_dependencies)
  907. snippets['dep_check_code'] = dep_check_code
  908. snippets['expression_code'] = expression_code
  909. def generate_code(**input_info):
  910. """
  911. Generates C source code from test suite file, data file, common
  912. helpers file and platform file.
  913. input_info expands to following parameters:
  914. funcs_file: Functions file object
  915. data_file: Data file object
  916. template_file: Template file object
  917. platform_file: Platform file object
  918. helpers_file: Helper functions file object
  919. suites_dir: Test suites dir
  920. c_file: Output C file object
  921. out_data_file: Output intermediate data file object
  922. :return:
  923. """
  924. funcs_file = input_info['funcs_file']
  925. data_file = input_info['data_file']
  926. template_file = input_info['template_file']
  927. platform_file = input_info['platform_file']
  928. helpers_file = input_info['helpers_file']
  929. suites_dir = input_info['suites_dir']
  930. c_file = input_info['c_file']
  931. out_data_file = input_info['out_data_file']
  932. for name, path in [('Functions file', funcs_file),
  933. ('Data file', data_file),
  934. ('Template file', template_file),
  935. ('Platform file', platform_file),
  936. ('Helpers code file', helpers_file),
  937. ('Suites dir', suites_dir)]:
  938. if not os.path.exists(path):
  939. raise IOError("ERROR: %s [%s] not found!" % (name, path))
  940. snippets = {'generator_script': os.path.basename(__file__)}
  941. read_code_from_input_files(platform_file, helpers_file,
  942. out_data_file, snippets)
  943. add_input_info(funcs_file, data_file, template_file,
  944. c_file, snippets)
  945. suite_dependencies, func_info = parse_function_file(funcs_file, snippets)
  946. generate_intermediate_data_file(data_file, out_data_file,
  947. suite_dependencies, func_info, snippets)
  948. write_test_source_file(template_file, c_file, snippets)
  949. def main():
  950. """
  951. Command line parser.
  952. :return:
  953. """
  954. parser = argparse.ArgumentParser(
  955. description='Dynamically generate test suite code.')
  956. parser.add_argument("-f", "--functions-file",
  957. dest="funcs_file",
  958. help="Functions file",
  959. metavar="FUNCTIONS_FILE",
  960. required=True)
  961. parser.add_argument("-d", "--data-file",
  962. dest="data_file",
  963. help="Data file",
  964. metavar="DATA_FILE",
  965. required=True)
  966. parser.add_argument("-t", "--template-file",
  967. dest="template_file",
  968. help="Template file",
  969. metavar="TEMPLATE_FILE",
  970. required=True)
  971. parser.add_argument("-s", "--suites-dir",
  972. dest="suites_dir",
  973. help="Suites dir",
  974. metavar="SUITES_DIR",
  975. required=True)
  976. parser.add_argument("--helpers-file",
  977. dest="helpers_file",
  978. help="Helpers file",
  979. metavar="HELPERS_FILE",
  980. required=True)
  981. parser.add_argument("-p", "--platform-file",
  982. dest="platform_file",
  983. help="Platform code file",
  984. metavar="PLATFORM_FILE",
  985. required=True)
  986. parser.add_argument("-o", "--out-dir",
  987. dest="out_dir",
  988. help="Dir where generated code and scripts are copied",
  989. metavar="OUT_DIR",
  990. required=True)
  991. args = parser.parse_args()
  992. data_file_name = os.path.basename(args.data_file)
  993. data_name = os.path.splitext(data_file_name)[0]
  994. out_c_file = os.path.join(args.out_dir, data_name + '.c')
  995. out_data_file = os.path.join(args.out_dir, data_name + '.datax')
  996. out_c_file_dir = os.path.dirname(out_c_file)
  997. out_data_file_dir = os.path.dirname(out_data_file)
  998. for directory in [out_c_file_dir, out_data_file_dir]:
  999. if not os.path.exists(directory):
  1000. os.makedirs(directory)
  1001. generate_code(funcs_file=args.funcs_file, data_file=args.data_file,
  1002. template_file=args.template_file,
  1003. platform_file=args.platform_file,
  1004. helpers_file=args.helpers_file, suites_dir=args.suites_dir,
  1005. c_file=out_c_file, out_data_file=out_data_file)
  1006. if __name__ == "__main__":
  1007. try:
  1008. main()
  1009. except GeneratorInputError as err:
  1010. sys.exit("%s: input error: %s" %
  1011. (os.path.basename(sys.argv[0]), str(err)))