blob: 45f15a164e9859e18ff36fed1fa9995c162b97fd [file] [log] [blame]
Gilles Peskine878acd62019-08-01 23:32:38 +02001#!/usr/bin/env python3
2
3"""Test helper for the Mbed TLS configuration file tool
4
5Run config.py with various parameters and write the results to files.
6
7This is a harness to help regression testing, not a functional tester.
8Sample usage:
9
10 test_config_script.py -d old
11 ## Modify config.py and/or config.h ##
12 test_config_script.py -d new
13 diff -ru old new
14"""
15
16## Copyright (C) 2019, ARM Limited, All Rights Reserved
17## SPDX-License-Identifier: Apache-2.0
18##
19## Licensed under the Apache License, Version 2.0 (the "License"); you may
20## not use this file except in compliance with the License.
21## You may obtain a copy of the License at
22##
23## http://www.apache.org/licenses/LICENSE-2.0
24##
25## Unless required by applicable law or agreed to in writing, software
26## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
27## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28## See the License for the specific language governing permissions and
29## limitations under the License.
30##
31## This file is part of Mbed TLS (https://tls.mbed.org)
32
33import argparse
34import glob
35import os
36import re
37import shutil
38import subprocess
39
40OUTPUT_FILE_PREFIX = 'config-'
41
42def output_file_name(directory, stem, extension):
43 return os.path.join(directory,
44 '{}{}.{}'.format(OUTPUT_FILE_PREFIX,
45 stem, extension))
46
47def cleanup_directory(directory):
48 """Remove old output files."""
49 for extension in []:
50 pattern = output_file_name(directory, '*', extension)
51 filenames = glob.glob(pattern)
52 for filename in filenames:
53 os.remove(filename)
54
55def prepare_directory(directory):
56 """Create the output directory if it doesn't exist yet.
57
58 If there are old output files, remove them.
59 """
60 if os.path.exists(directory):
61 cleanup_directory(directory)
62 else:
63 os.makedirs(directory)
64
65def guess_presets_from_help(help_text):
66 """Figure out what presets the script supports.
67
68 help_text should be the output from running the script with --help.
69 """
70 # Try the output format from config.py
71 hits = re.findall(r'\{([-\w,]+)\}', help_text)
72 for hit in hits:
73 words = set(hit.split(','))
74 if 'get' in words and 'set' in words and 'unset' in words:
75 words.remove('get')
76 words.remove('set')
77 words.remove('unset')
78 return words
79 # Try the output format from config.pl
80 hits = re.findall(r'\n +([-\w]+) +- ', help_text)
81 if hits:
82 return hits
83 raise Exception("Unable to figure out supported presets. Pass the '-p' option.")
84
85def list_presets(options):
86 """Return the list of presets to test.
87
88 The list is taken from the command line if present, otherwise it is
89 extracted from running the config script with --help.
90 """
91 if options.presets:
92 return re.split(r'[ ,]+', options.presets)
93 else:
94 help_text = subprocess.run([options.script, '--help'],
95 stdout=subprocess.PIPE,
96 stderr=subprocess.STDOUT).stdout
97 return guess_presets_from_help(help_text.decode('ascii'))
98
99def run_one(options, args):
100 """Run the config script with the given arguments.
101
102 Write the following files:
103 * config-xxx.h: modified file.
104 * config-xxx.out: standard output.
105 * config-xxx.err: standard output.
106 * config-xxx.status: exit code.
107 """
108 stem = '-'.join(args)
109 data_filename = output_file_name(options.output_directory, stem, 'h')
110 stdout_filename = output_file_name(options.output_directory, stem, 'out')
111 stderr_filename = output_file_name(options.output_directory, stem, 'err')
112 status_filename = output_file_name(options.output_directory, stem, 'status')
113 shutil.copy(options.input_file, data_filename)
114 # Pass only the file basename, not the full path, to avoid getting the
115 # directory name in error messages, which would make comparisons
116 # between output directories more difficult.
117 cmd = [os.path.abspath(options.script),
118 '-f', os.path.basename(data_filename)]
119 with open(stdout_filename, 'wb') as out:
120 with open(stderr_filename, 'wb') as err:
121 status = subprocess.call(cmd + args,
122 cwd=options.output_directory,
123 stdin=subprocess.DEVNULL,
124 stdout=out, stderr=err)
125 with open(status_filename, 'w') as status_file:
126 status_file.write('{}\n'.format(status))
127
Gilles Peskinefd7ad332019-09-19 12:18:23 +0200128### A list of symbols to test with.
129### This script currently tests what happens when you change a symbol from
130### having a value to not having a value or vice versa. This is not
131### necessarily useful behavior, and we may not consider it a bug if
132### config.py stops handling that case correctly.
Gilles Peskine878acd62019-08-01 23:32:38 +0200133TEST_SYMBOLS = [
Gilles Peskinefd7ad332019-09-19 12:18:23 +0200134 'CUSTOM_SYMBOL', # does not exist
135 'MBEDTLS_AES_C', # set, no value
136 'MBEDTLS_MPI_MAX_SIZE', # unset, has a value
137 'MBEDTLS_NO_UDBL_DIVISION', # unset, in "System support"
138 'MBEDTLS_PLATFORM_ZEROIZE_ALT', # unset, in "Customisation configuration options"
Gilles Peskine878acd62019-08-01 23:32:38 +0200139]
140
141def run_all(options):
142 """Run all the command lines to test."""
143 presets = list_presets(options)
144 for preset in presets:
145 run_one(options, [preset])
146 for symbol in TEST_SYMBOLS:
Gilles Peskine61695e72019-09-13 15:17:01 +0200147 run_one(options, ['get', symbol])
Gilles Peskine878acd62019-08-01 23:32:38 +0200148 run_one(options, ['set', symbol])
149 run_one(options, ['--force', 'set', symbol])
Gilles Peskine878acd62019-08-01 23:32:38 +0200150 run_one(options, ['set', symbol, 'value'])
151 run_one(options, ['--force', 'set', symbol, 'value'])
Gilles Peskinef6860422019-09-04 22:51:47 +0200152 run_one(options, ['unset', symbol])
Gilles Peskine878acd62019-08-01 23:32:38 +0200153
154def main():
155 """Command line entry point."""
156 parser = argparse.ArgumentParser(description=__doc__,
157 formatter_class=argparse.RawDescriptionHelpFormatter)
158 parser.add_argument('-d', metavar='DIR',
159 dest='output_directory', required=True,
160 help="""Output directory.""")
161 parser.add_argument('-f', metavar='FILE',
162 dest='input_file', default='include/mbedtls/config.h',
163 help="""Config file (default: %(default)s).""")
164 parser.add_argument('-p', metavar='PRESET,...',
165 dest='presets',
166 help="""Presets to test (default: guessed from --help).""")
167 parser.add_argument('-s', metavar='FILE',
168 dest='script', default='scripts/config.py',
169 help="""Configuration script (default: %(default)s).""")
170 options = parser.parse_args()
171 prepare_directory(options.output_directory)
172 run_all(options)
173
174if __name__ == '__main__':
175 main()