blob: 6af6f8d5455e41e31c89ba816d3a2341b00f573f [file] [log] [blame]
Darryl Greend5802922018-05-08 15:30:59 +01001#!/usr/bin/env python3
2"""
3This file is part of Mbed TLS (https://tls.mbed.org)
4
5Copyright (c) 2018, Arm Limited, All Rights Reserved
6
7Purpose
8
9This script confirms that the naming of all symbols and identifiers in mbed
10TLS are consistent with the house style and are also self-consistent.
11"""
12import os
13import sys
14import traceback
15import re
16import shutil
17import subprocess
18import logging
19
20
21class NameCheck(object):
22 def __init__(self):
23 self.log = None
24 self.setup_logger()
25 self.check_repo_path()
26 self.return_code = 0
27 self.excluded_files = ["compat-1.3.h"]
28 self.header_files = self.get_files(os.path.join("include", "mbedtls"))
29 self.library_files = self.get_files("library")
30 self.macros = []
31 self.MBED_names = []
32 self.enum_consts = []
33 self.identifiers = []
34 self.actual_macros = []
35 self.symbols = []
36 self.macro_pattern = r"#define (?P<macro>\w+)"
37 self.MBED_pattern = r"\bMBED.+?_[A-Z0-9_]*"
38 self.symbol_pattern = r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)"
39 self.identifier_check_pattern = r"^mbedtls_[0-9a-z_]*[0-9a-z]$"
40 self.decls_pattern = (
41 r"^(extern \"C\"|(typedef )?(struct|enum)( {)?$|};?$|$)"
42 )
43 self.macro_const_check_pattern = (
44 r"^MBEDTLS_[0-9A-Z_]*[0-9A-Z]$|^YOTTA_[0-9A-Z_]*[0-9A-Z]$"
45 )
46 self.typo_check_pattern = r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$"
47 self.non_macros = (
48 "asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
49 )
50
51 def set_return_code(self, return_code):
52 if return_code > self.return_code:
53 self.return_code = return_code
54
55 def setup_logger(self):
56 self.log = logging.getLogger()
57 self.log.setLevel(logging.INFO)
58 self.log.addHandler(logging.StreamHandler())
59
60 def check_repo_path(self):
61 current_dir = os.path.realpath('.')
62 root_dir = os.path.dirname(os.path.dirname(
63 os.path.dirname(os.path.realpath(__file__))))
64 if current_dir != root_dir:
65 raise Exception("Must be run from Mbed TLS root")
66
67 def get_files(self, directory):
68 filenames = []
69 for root, dirs, files in sorted(os.walk(directory)):
70 for filename in sorted(files):
71 if (filename not in self.excluded_files and
72 filename.endswith((".c", ".h"))):
73 filenames.append(os.path.join(root, filename))
74 return filenames
75
76 def get_macros(self):
77 for header_file in self.header_files:
78 with open(header_file, "r") as header:
79 for line in iter(header.readline, ""):
80 macro = re.search(self.macro_pattern, line)
81 if (macro and not
82 macro.group("macro").startswith(self.non_macros)):
83 self.macros.append((macro.group("macro"), header_file))
84 self.macros = list(set(self.macros))
85
86 def get_MBED_names(self):
87 for file_group in [self.header_files, self.library_files]:
88 for filename in file_group:
89 with open(filename, "r") as f:
90 for line in iter(f.readline, ""):
91 mbed_names = re.findall(self.MBED_pattern, line)
92 if mbed_names:
93 for name in mbed_names:
94 self.MBED_names.append((name, filename))
95 self.MBED_names = list(set(self.MBED_names))
96
97 def get_enum_consts(self):
98 for header_file in self.header_files:
99 state = 0
100 with open(header_file, "r") as header:
101 for line in iter(header.readline, ""):
102 if state is 0 and re.match(r"^(typedef )?enum {", line):
103 state = 1
104 elif state is 0 and re.match(r"^(typedef )?enum", line):
105 state = 2
106 elif state is 2 and re.match(r"^{", line):
107 state = 1
108 elif state is 1 and re.match(r"^}", line):
109 state = 0
110 elif state is 1:
111 enum_const = re.match(r"^\s*(?P<enum_const>\w+)", line)
112 if enum_const:
113 self.enum_consts.append(
114 (enum_const.group("enum_const"), header_file)
115 )
116
117 def line_contains_declaration(self, line):
118 return (re.match(r"^[^ /#{]", line)
119 and not re.match(self.decls_pattern, line))
120
121 def get_identifier_from_declaration(self, declaration):
122 identifier = re.search(
123 r"([a-zA-Z_][a-zA-Z0-9_]*)\(|"
124 r"\(\*(.+)\)\(|"
125 r"(\w+)\W*$",
126 declaration
127 )
128 if identifier:
129 for group in identifier.groups():
130 if group:
131 return group
132 self.log.error(declaration)
133 raise Exception("No identifier found")
134
135 def get_identifiers(self):
136 for header_file in self.header_files:
137 with open(header_file, "r") as header:
138 for line in iter(header.readline, ""):
139 if self.line_contains_declaration(line):
140 self.identifiers.append(
141 (self.get_identifier_from_declaration(line),
142 header_file)
143 )
144
145 def get_symbols(self):
146 try:
147 shutil.copy("include/mbedtls/config.h",
148 "include/mbedtls/config.h.bak")
149 subprocess.run(
150 ["perl", "scripts/config.pl", "full"],
151 encoding=sys.stdout.encoding,
152 check=True
153 )
154 my_environment = os.environ.copy()
155 my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
156 subprocess.run(
157 ["make", "clean", "lib"],
158 env=my_environment,
159 encoding=sys.stdout.encoding,
160 stdout=subprocess.PIPE,
161 stderr=subprocess.STDOUT,
162 check=True
163 )
164 shutil.move("include/mbedtls/config.h.bak",
165 "include/mbedtls/config.h")
166 nm_output = ""
167 for lib in ["library/libmbedcrypto.a",
168 "library/libmbedtls.a",
169 "library/libmbedx509.a"]:
170 nm_output += subprocess.run(
171 ["nm", "-og", lib],
172 encoding=sys.stdout.encoding,
173 stdout=subprocess.PIPE,
174 stderr=subprocess.STDOUT,
175 check=True
176 ).stdout
177 for line in nm_output.splitlines():
178 if not re.match(r"^\S+: +U |^$|^\S+:$", line):
179 symbol = re.match(self.symbol_pattern, line)
180 if symbol:
181 self.symbols.append(symbol.group('symbol'))
182 else:
183 self.log.error(line)
184 self.symbols.sort()
185 subprocess.run(
186 ["make", "clean"],
187 encoding=sys.stdout.encoding,
188 check=True
189 )
190 except subprocess.CalledProcessError as error:
191 self.log.error(error)
192 self.set_return_code(2)
193
194 def check_symbols_declared_in_header(self):
195 identifiers = [x[0] for x in self.identifiers]
196 bad_names = []
197 for symbol in self.symbols:
198 if symbol not in identifiers:
199 bad_names.append(symbol)
200 if bad_names:
201 self.set_return_code(1)
202 self.log.info("Names of identifiers: FAIL")
203 for name in bad_names:
204 self.log.info(name)
205 else:
206 self.log.info("Names of identifiers: PASS")
207
208 def check_group(self, group_to_check, check_pattern, name):
209 bad_names = []
210 for item in group_to_check:
211 if not re.match(check_pattern, item[0]):
212 bad_names.append("{} - {}".format(item[0], item[1]))
213 if bad_names:
214 self.set_return_code(1)
215 self.log.info("Names of {}: FAIL".format(name))
216 for name in bad_names:
217 self.log.info(name)
218 else:
219 self.log.info("Names of {}: PASS".format(name))
220
221 def check_for_typos(self):
222 bad_names = []
223 all_caps_names = list(set(
224 [x[0] for x in self.actual_macros + self.enum_consts]
225 ))
226 for name in self.MBED_names:
227 if name[0] not in all_caps_names:
228 if not re.search(self.typo_check_pattern, name[0]):
229 bad_names.append("{} - {}".format(name[0], name[1]))
230 if bad_names:
231 self.set_return_code(1)
232 self.log.info("Likely typos: FAIL")
233 for name in bad_names:
234 self.log.info(name)
235 else:
236 self.log.info("Likely typos: PASS")
237
238 def get_names_from_source_code(self):
239 self.log.info("Analysing source code...")
240 self.get_macros()
241 self.get_enum_consts()
242 self.get_identifiers()
243 self.get_symbols()
244 self.get_MBED_names()
245 self.actual_macros = list(set(self.macros) - set(self.identifiers))
246 self.log.info("{} macros".format(len(self.macros)))
247 self.log.info("{} enum-consts".format(len(self.enum_consts)))
248 self.log.info("{} identifiers".format(len(self.identifiers)))
249 self.log.info("{} exported-symbols".format(len(self.symbols)))
250
251 def check_names(self):
252 self.check_symbols_declared_in_header()
253 for group, check_pattern, name in [
254 (self.actual_macros, self.macro_const_check_pattern,
255 "actual-macros"),
256 (self.enum_consts, self.macro_const_check_pattern,
257 "enum-consts"),
258 (self.identifiers, self.identifier_check_pattern,
259 "identifiers")]:
260 self.check_group(group, check_pattern, name)
261 self.check_for_typos()
262
263
264def run_main():
265 try:
266 name_check = NameCheck()
267 name_check.get_names_from_source_code()
268 name_check.check_names()
269 sys.exit(name_check.return_code)
270 except Exception:
271 traceback.print_exc()
272 sys.exit(2)
273
274
275if __name__ == "__main__":
276 run_main()