blob: 113854c28c8e42ab9e1aeae6a8c3a04d3648f348 [file] [log] [blame]
Yuto Takano39639672021-08-05 19:47:48 +01001#!/usr/bin/env python3
2#
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
Darryl Greend5802922018-05-08 15:30:59 +010018"""
Yuto Takano39639672021-08-05 19:47:48 +010019This script confirms that the naming of all symbols and identifiers in Mbed TLS
Yuto Takano159255a2021-08-06 17:00:28 +010020are consistent with the house style and are also self-consistent. It only runs
21on Linux and macOS since it depends on nm.
22
Yuto Takano55c6c872021-08-09 15:35:19 +010023It contains two major Python classes, CodeParser and NameChecker. They both have
24a comprehensive "run-all" function (comprehensive_parse() and perform_checks())
25but the individual functions can also be used for specific needs.
26
27CodeParser makes heavy use of regular expressions to parse the code, and is
28dependent on the current code formatting. Many Python C parser libraries require
29preprocessed C code, which means no macro parsing. Compiler tools are also not
30very helpful when we want the exact location in the original source (which
31becomes impossible when e.g. comments are stripped).
32
33NameChecker performs the following checks:
Yuto Takano81528c02021-08-06 16:22:06 +010034
35- All exported and available symbols in the library object files, are explicitly
Yuto Takano159255a2021-08-06 17:00:28 +010036 declared in the header files. This uses the nm command.
Yuto Takano81528c02021-08-06 16:22:06 +010037- All macros, constants, and identifiers (function names, struct names, etc)
Yuto Takano55c6c872021-08-09 15:35:19 +010038 follow the required regex pattern.
Yuto Takano81528c02021-08-06 16:22:06 +010039- Typo checking: All words that begin with MBED exist as macros or constants.
Yuto Takanofc54dfb2021-08-07 17:18:28 +010040
Yuto Takano55c6c872021-08-09 15:35:19 +010041The script returns 0 on success, 1 on test failure, and 2 if there is a script
Yuto Takano8246eb82021-08-16 10:37:24 +010042error. It must be run from Mbed TLS root.
Darryl Greend5802922018-05-08 15:30:59 +010043"""
Yuto Takano39639672021-08-05 19:47:48 +010044
45import argparse
Yuto Takano977e07f2021-08-09 11:56:15 +010046import glob
Yuto Takano39639672021-08-05 19:47:48 +010047import textwrap
Darryl Greend5802922018-05-08 15:30:59 +010048import os
49import sys
50import traceback
51import re
52import shutil
53import subprocess
54import logging
55
Yuto Takano81528c02021-08-06 16:22:06 +010056# Naming patterns to check against. These are defined outside the NameCheck
57# class for ease of modification.
Yuto Takanobb7dca42021-08-05 19:57:58 +010058MACRO_PATTERN = r"^(MBEDTLS|PSA)_[0-9A-Z_]*[0-9A-Z]$"
Yuto Takano81528c02021-08-06 16:22:06 +010059CONSTANTS_PATTERN = MACRO_PATTERN
Yuto Takanoc1838932021-08-05 19:52:09 +010060IDENTIFIER_PATTERN = r"^(mbedtls|psa)_[0-9a-z_]*[0-9a-z]$"
Yuto Takano39639672021-08-05 19:47:48 +010061
Yuto Takanod93fa372021-08-06 23:05:55 +010062class Match(): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +010063 """
64 A class representing a match, together with its found position.
65
66 Fields:
67 * filename: the file that the match was in.
68 * line: the full line containing the match.
Yuto Takanod93fa372021-08-06 23:05:55 +010069 * pos: a tuple of (line_no, start, end) positions on the file line where the
70 match is.
Yuto Takano81528c02021-08-06 16:22:06 +010071 * name: the match itself.
72 """
Yuto Takanod93fa372021-08-06 23:05:55 +010073 def __init__(self, filename, line, pos, name):
Yuto Takano39639672021-08-05 19:47:48 +010074 self.filename = filename
75 self.line = line
76 self.pos = pos
77 self.name = name
Yuto Takano39639672021-08-05 19:47:48 +010078
Yuto Takanoa4e75122021-08-06 17:23:28 +010079 def __str__(self):
Yuto Takanofb86ac72021-08-16 10:32:40 +010080 """
81 Return a formatted code listing representation of the erroneous line.
82 """
83 gutter = format(self.pos[0], "4d")
Yuto Takano381fda82021-08-06 23:37:20 +010084 underline = self.pos[1] * " " + (self.pos[2] - self.pos[1]) * "^"
85
Yuto Takanoa4e75122021-08-06 17:23:28 +010086 return (
Yuto Takanofb86ac72021-08-16 10:32:40 +010087 " {0} |\n".format(" " * len(gutter)) +
Yuto Takano381fda82021-08-06 23:37:20 +010088 " {0} | {1}".format(gutter, self.line) +
Yuto Takanofb86ac72021-08-16 10:32:40 +010089 " {0} | {1}\n".format(" " * len(gutter), underline)
Yuto Takanoa4e75122021-08-06 17:23:28 +010090 )
Yuto Takanod93fa372021-08-06 23:05:55 +010091
92class Problem(): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +010093 """
94 A parent class representing a form of static analysis error.
Yuto Takano81528c02021-08-06 16:22:06 +010095 """
Yuto Takano39639672021-08-05 19:47:48 +010096 def __init__(self):
Yuto Takanod70d4462021-08-09 12:45:51 +010097 self.quiet = False
Yuto Takano39639672021-08-05 19:47:48 +010098 self.textwrapper = textwrap.TextWrapper()
Yuto Takano81528c02021-08-06 16:22:06 +010099 self.textwrapper.width = 80
Yuto Takanoa4e75122021-08-06 17:23:28 +0100100 self.textwrapper.initial_indent = " > "
Yuto Takano81528c02021-08-06 16:22:06 +0100101 self.textwrapper.subsequent_indent = " "
Yuto Takano39639672021-08-05 19:47:48 +0100102
Yuto Takanod93fa372021-08-06 23:05:55 +0100103class SymbolNotInHeader(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100104 """
105 A problem that occurs when an exported/available symbol in the object file
106 is not explicitly declared in header files. Created with
107 NameCheck.check_symbols_declared_in_header()
108
109 Fields:
110 * symbol_name: the name of the symbol.
111 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100112 def __init__(self, symbol_name):
Yuto Takano39639672021-08-05 19:47:48 +0100113 self.symbol_name = symbol_name
114 Problem.__init__(self)
115
116 def __str__(self):
Yuto Takano55614b52021-08-07 01:00:18 +0100117 if self.quiet:
118 return "{0}".format(self.symbol_name)
119
Yuto Takano39639672021-08-05 19:47:48 +0100120 return self.textwrapper.fill(
121 "'{0}' was found as an available symbol in the output of nm, "
122 "however it was not declared in any header files."
123 .format(self.symbol_name))
124
Yuto Takanod93fa372021-08-06 23:05:55 +0100125class PatternMismatch(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100126 """
127 A problem that occurs when something doesn't match the expected pattern.
128 Created with NameCheck.check_match_pattern()
129
130 Fields:
131 * pattern: the expected regex pattern
132 * match: the Match object in question
133 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100134 def __init__(self, pattern, match):
Yuto Takano39639672021-08-05 19:47:48 +0100135 self.pattern = pattern
136 self.match = match
137 Problem.__init__(self)
Yuto Takano81528c02021-08-06 16:22:06 +0100138
Yuto Takano39639672021-08-05 19:47:48 +0100139 def __str__(self):
Yuto Takano55614b52021-08-07 01:00:18 +0100140 if self.quiet:
Yuto Takanod70d4462021-08-09 12:45:51 +0100141 return (
Yuto Takano206b0222021-08-10 11:30:43 +0100142 "{0}:{1}:{2}"
Yuto Takanod70d4462021-08-09 12:45:51 +0100143 .format(self.match.filename, self.match.pos[0], self.match.name)
144 )
Yuto Takano55614b52021-08-07 01:00:18 +0100145
Yuto Takano39639672021-08-05 19:47:48 +0100146 return self.textwrapper.fill(
Yuto Takanoa4e75122021-08-06 17:23:28 +0100147 "{0}:{1}: '{2}' does not match the required pattern '{3}'."
148 .format(
149 self.match.filename,
Yuto Takanod93fa372021-08-06 23:05:55 +0100150 self.match.pos[0],
Yuto Takanoa4e75122021-08-06 17:23:28 +0100151 self.match.name,
Yuto Takanod70d4462021-08-09 12:45:51 +0100152 self.pattern
153 )
154 ) + "\n" + str(self.match)
Yuto Takano39639672021-08-05 19:47:48 +0100155
Yuto Takanod93fa372021-08-06 23:05:55 +0100156class Typo(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100157 """
158 A problem that occurs when a word using MBED doesn't appear to be defined as
159 constants nor enum values. Created with NameCheck.check_for_typos()
160
161 Fields:
162 * match: the Match object of the MBED name in question.
163 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100164 def __init__(self, match):
Yuto Takano39639672021-08-05 19:47:48 +0100165 self.match = match
166 Problem.__init__(self)
Yuto Takano81528c02021-08-06 16:22:06 +0100167
Yuto Takano39639672021-08-05 19:47:48 +0100168 def __str__(self):
Yuto Takano55614b52021-08-07 01:00:18 +0100169 if self.quiet:
Yuto Takanod70d4462021-08-09 12:45:51 +0100170 return (
171 "{0}:{1}:{2}"
172 .format(self.match.filename, self.match.pos[0], self.match.name)
173 )
Yuto Takano55614b52021-08-07 01:00:18 +0100174
Yuto Takano39639672021-08-05 19:47:48 +0100175 return self.textwrapper.fill(
Yuto Takanoa4e75122021-08-06 17:23:28 +0100176 "{0}:{1}: '{2}' looks like a typo. It was not found in any "
177 "macros or any enums. If this is not a typo, put "
178 "//no-check-names after it."
Yuto Takanod70d4462021-08-09 12:45:51 +0100179 .format(self.match.filename, self.match.pos[0], self.match.name)
180 ) + "\n" + str(self.match)
Darryl Greend5802922018-05-08 15:30:59 +0100181
Yuto Takano55c6c872021-08-09 15:35:19 +0100182class CodeParser():
Yuto Takano81528c02021-08-06 16:22:06 +0100183 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100184 Class for retrieving files and parsing the code. This can be used
185 independently of the checks that NameChecker performs, for example for
186 list_internal_identifiers.py.
Yuto Takano81528c02021-08-06 16:22:06 +0100187 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100188 def __init__(self, log):
189 self.log = log
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100190 self.check_repo_path()
Yuto Takano977e07f2021-08-09 11:56:15 +0100191
Yuto Takano8e9a2192021-08-09 14:48:53 +0100192 # Memo for storing "glob expression": set(filepaths)
193 self.files = {}
194
Yuto Takano977e07f2021-08-09 11:56:15 +0100195 # Globally excluded filenames
Yuto Takano8e9a2192021-08-09 14:48:53 +0100196 self.excluded_files = ["**/bn_mul", "**/compat-2.x.h"]
Yuto Takano977e07f2021-08-09 11:56:15 +0100197
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100198 @staticmethod
199 def check_repo_path():
200 """
201 Check that the current working directory is the project root, and throw
202 an exception if not.
203 """
204 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
205 raise Exception("This script must be run from Mbed TLS root")
206
Yuto Takano55c6c872021-08-09 15:35:19 +0100207 def comprehensive_parse(self):
Yuto Takano39639672021-08-05 19:47:48 +0100208 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100209 Comprehensive ("default") function to call each parsing function and
210 retrieve various elements of the code, together with the source location.
Darryl Greend5802922018-05-08 15:30:59 +0100211
Yuto Takano55c6c872021-08-09 15:35:19 +0100212 Returns a dict of parsed item key to the corresponding List of Matches.
Yuto Takano81528c02021-08-06 16:22:06 +0100213 """
214 self.log.info("Parsing source code...")
Yuto Takanod24e0372021-08-06 16:42:33 +0100215 self.log.debug(
Yuto Takano50953432021-08-09 14:54:36 +0100216 "The following files are excluded from the search: {}"
Yuto Takanod24e0372021-08-06 16:42:33 +0100217 .format(str(self.excluded_files))
218 )
Yuto Takano81528c02021-08-06 16:22:06 +0100219
Yuto Takano8e9a2192021-08-09 14:48:53 +0100220 all_macros = self.parse_macros([
221 "include/mbedtls/*.h",
222 "include/psa/*.h",
223 "library/*.h",
224 "tests/include/test/drivers/*.h",
Yuto Takanod70d4462021-08-09 12:45:51 +0100225 "3rdparty/everest/include/everest/everest.h",
226 "3rdparty/everest/include/everest/x25519.h"
Yuto Takano8e9a2192021-08-09 14:48:53 +0100227 ])
228 enum_consts = self.parse_enum_consts([
229 "include/mbedtls/*.h",
230 "library/*.h",
231 "3rdparty/everest/include/everest/everest.h",
232 "3rdparty/everest/include/everest/x25519.h"
233 ])
234 identifiers = self.parse_identifiers([
235 "include/mbedtls/*.h",
236 "include/psa/*.h",
237 "library/*.h",
238 "3rdparty/everest/include/everest/everest.h",
239 "3rdparty/everest/include/everest/x25519.h"
240 ])
241 mbed_words = self.parse_mbed_words([
242 "include/mbedtls/*.h",
243 "include/psa/*.h",
244 "library/*.h",
245 "3rdparty/everest/include/everest/everest.h",
246 "3rdparty/everest/include/everest/x25519.h",
247 "library/*.c",
Yuto Takano81528c02021-08-06 16:22:06 +0100248 "3rdparty/everest/library/everest.c",
Yuto Takanod70d4462021-08-09 12:45:51 +0100249 "3rdparty/everest/library/x25519.c"
Yuto Takano8e9a2192021-08-09 14:48:53 +0100250 ])
Yuto Takano81528c02021-08-06 16:22:06 +0100251 symbols = self.parse_symbols()
252
253 # Remove identifier macros like mbedtls_printf or mbedtls_calloc
254 identifiers_justname = [x.name for x in identifiers]
255 actual_macros = []
256 for macro in all_macros:
257 if macro.name not in identifiers_justname:
258 actual_macros.append(macro)
259
260 self.log.debug("Found:")
Yuto Takanod70d4462021-08-09 12:45:51 +0100261 self.log.debug(" {} Total Macros".format(len(all_macros)))
Yuto Takano81528c02021-08-06 16:22:06 +0100262 self.log.debug(" {} Non-identifier Macros".format(len(actual_macros)))
263 self.log.debug(" {} Enum Constants".format(len(enum_consts)))
264 self.log.debug(" {} Identifiers".format(len(identifiers)))
265 self.log.debug(" {} Exported Symbols".format(len(symbols)))
Yuto Takano55c6c872021-08-09 15:35:19 +0100266 return {
Yuto Takano81528c02021-08-06 16:22:06 +0100267 "macros": actual_macros,
268 "enum_consts": enum_consts,
269 "identifiers": identifiers,
270 "symbols": symbols,
Yuto Takanod93fa372021-08-06 23:05:55 +0100271 "mbed_words": mbed_words
Yuto Takano81528c02021-08-06 16:22:06 +0100272 }
273
Yuto Takano55c6c872021-08-09 15:35:19 +0100274 def get_files(self, include_wildcards, exclude_wildcards):
275 """
276 Get all files that match any of the UNIX-style wildcards. While the
277 check_names script is designed only for use on UNIX/macOS (due to nm),
278 this function alone would work fine on Windows even with forward slashes
279 in the wildcard.
280
281 Args:
282 * include_wildcards: a List of shell-style wildcards to match filepaths.
283 * exclude_wildcards: a List of shell-style wildcards to exclude.
284
285 Returns a List of relative filepaths.
286 """
287 accumulator = set()
288
289 # exclude_wildcards may be None. Also, consider the global exclusions.
290 exclude_wildcards = (exclude_wildcards or []) + self.excluded_files
291
292 # Perform set union on the glob results. Memoise individual sets.
293 for include_wildcard in include_wildcards:
294 if include_wildcard not in self.files:
295 self.files[include_wildcard] = set(glob.glob(
296 include_wildcard,
297 recursive=True
298 ))
299
300 accumulator = accumulator.union(self.files[include_wildcard])
301
302 # Perform set difference to exclude. Also use the same memo since their
303 # behaviour is pretty much identical and it can benefit from the cache.
304 for exclude_wildcard in exclude_wildcards:
305 if exclude_wildcard not in self.files:
306 self.files[exclude_wildcard] = set(glob.glob(
307 exclude_wildcard,
308 recursive=True
309 ))
310
311 accumulator = accumulator.difference(self.files[exclude_wildcard])
312
313 return list(accumulator)
314
Yuto Takano8e9a2192021-08-09 14:48:53 +0100315 def parse_macros(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100316 """
317 Parse all macros defined by #define preprocessor directives.
318
319 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100320 * include: A List of glob expressions to look for files through.
321 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100322
323 Returns a List of Match objects for the found macros.
Yuto Takano39639672021-08-05 19:47:48 +0100324 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100325 macro_regex = re.compile(r"# *define +(?P<macro>\w+)")
326 exclusions = (
Yuto Takano39639672021-08-05 19:47:48 +0100327 "asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
328 )
329
Yuto Takano50953432021-08-09 14:54:36 +0100330 files = self.get_files(include, exclude)
331 self.log.debug("Looking for macros in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100332
Yuto Takano50953432021-08-09 14:54:36 +0100333 macros = []
334 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100335 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100336 for line_no, line in enumerate(header):
Yuto Takanod93fa372021-08-06 23:05:55 +0100337 for macro in macro_regex.finditer(line):
Yuto Takanod70d4462021-08-09 12:45:51 +0100338 if macro.group("macro").startswith(exclusions):
339 continue
340
341 macros.append(Match(
342 header_file,
343 line,
344 (line_no, macro.start(), macro.end()),
345 macro.group("macro")))
Darryl Greend5802922018-05-08 15:30:59 +0100346
Yuto Takano39639672021-08-05 19:47:48 +0100347 return macros
Darryl Greend5802922018-05-08 15:30:59 +0100348
Yuto Takano8e9a2192021-08-09 14:48:53 +0100349 def parse_mbed_words(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100350 """
Yuto Takanob47b5042021-08-07 00:42:54 +0100351 Parse all words in the file that begin with MBED, in and out of macros,
352 comments, anything.
Yuto Takano39639672021-08-05 19:47:48 +0100353
354 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100355 * include: A List of glob expressions to look for files through.
356 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100357
358 Returns a List of Match objects for words beginning with MBED.
Yuto Takano39639672021-08-05 19:47:48 +0100359 """
Yuto Takanob47b5042021-08-07 00:42:54 +0100360 # Typos of TLS are common, hence the broader check below than MBEDTLS.
Yuto Takanod93fa372021-08-06 23:05:55 +0100361 mbed_regex = re.compile(r"\bMBED.+?_[A-Z0-9_]*")
362 exclusions = re.compile(r"// *no-check-names|#error")
363
Yuto Takano50953432021-08-09 14:54:36 +0100364 files = self.get_files(include, exclude)
365 self.log.debug("Looking for MBED words in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100366
Yuto Takano50953432021-08-09 14:54:36 +0100367 mbed_words = []
368 for filename in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100369 with open(filename, "r", encoding="utf-8") as fp:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100370 for line_no, line in enumerate(fp):
Yuto Takanod93fa372021-08-06 23:05:55 +0100371 if exclusions.search(line):
Yuto Takanoc62b4082021-08-05 20:17:07 +0100372 continue
Yuto Takano81528c02021-08-06 16:22:06 +0100373
Yuto Takanod93fa372021-08-06 23:05:55 +0100374 for name in mbed_regex.finditer(line):
375 mbed_words.append(Match(
Yuto Takano39639672021-08-05 19:47:48 +0100376 filename,
377 line,
Yuto Takanod93fa372021-08-06 23:05:55 +0100378 (line_no, name.start(), name.end()),
Yuto Takano39639672021-08-05 19:47:48 +0100379 name.group(0)
380 ))
381
Yuto Takanod93fa372021-08-06 23:05:55 +0100382 return mbed_words
Yuto Takano39639672021-08-05 19:47:48 +0100383
Yuto Takano8e9a2192021-08-09 14:48:53 +0100384 def parse_enum_consts(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100385 """
386 Parse all enum value constants that are declared.
387
388 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100389 * include: A List of glob expressions to look for files through.
390 * exclude: A List of glob expressions for excluding files.
Yuto Takano39639672021-08-05 19:47:48 +0100391
Yuto Takano81528c02021-08-06 16:22:06 +0100392 Returns a List of Match objects for the findings.
Yuto Takano39639672021-08-05 19:47:48 +0100393 """
Yuto Takano50953432021-08-09 14:54:36 +0100394 files = self.get_files(include, exclude)
395 self.log.debug("Looking for enum consts in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100396
Yuto Takano50953432021-08-09 14:54:36 +0100397 enum_consts = []
398 for header_file in files:
Yuto Takano39639672021-08-05 19:47:48 +0100399 # Emulate a finite state machine to parse enum declarations.
Yuto Takano81528c02021-08-06 16:22:06 +0100400 # 0 = not in enum
401 # 1 = inside enum
402 # 2 = almost inside enum
Darryl Greend5802922018-05-08 15:30:59 +0100403 state = 0
Yuto Takanoa083d152021-08-07 00:25:59 +0100404 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100405 for line_no, line in enumerate(header):
Yuto Takano13ecd992021-08-06 16:56:52 +0100406 # Match typedefs and brackets only when they are at the
407 # beginning of the line -- if they are indented, they might
408 # be sub-structures within structs, etc.
Yuto Takanod93fa372021-08-06 23:05:55 +0100409 if state == 0 and re.match(r"^(typedef +)?enum +{", line):
Darryl Greend5802922018-05-08 15:30:59 +0100410 state = 1
Yuto Takanod93fa372021-08-06 23:05:55 +0100411 elif state == 0 and re.match(r"^(typedef +)?enum", line):
Darryl Greend5802922018-05-08 15:30:59 +0100412 state = 2
Yuto Takanod93fa372021-08-06 23:05:55 +0100413 elif state == 2 and re.match(r"^{", line):
Darryl Greend5802922018-05-08 15:30:59 +0100414 state = 1
Yuto Takanod93fa372021-08-06 23:05:55 +0100415 elif state == 1 and re.match(r"^}", line):
Darryl Greend5802922018-05-08 15:30:59 +0100416 state = 0
Yuto Takanod93fa372021-08-06 23:05:55 +0100417 elif state == 1 and not re.match(r" *#", line):
Yuto Takano13ecd992021-08-06 16:56:52 +0100418 enum_const = re.match(r" *(?P<enum_const>\w+)", line)
Yuto Takanod70d4462021-08-09 12:45:51 +0100419 if not enum_const:
420 continue
421
422 enum_consts.append(Match(
423 header_file,
424 line,
425 (line_no, enum_const.start(), enum_const.end()),
426 enum_const.group("enum_const")))
Yuto Takano81528c02021-08-06 16:22:06 +0100427
Yuto Takano39639672021-08-05 19:47:48 +0100428 return enum_consts
Darryl Greend5802922018-05-08 15:30:59 +0100429
Yuto Takano8e9a2192021-08-09 14:48:53 +0100430 def parse_identifiers(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100431 """
Yuto Takano8246eb82021-08-16 10:37:24 +0100432 Parse all lines of a header where a function/enum/struct/union/typedef
433 identifier is declared, based on some heuristics. Highly dependent on
434 formatting style.
Yuto Takanod70d4462021-08-09 12:45:51 +0100435 Note: .match() checks at the beginning of the string (implicit ^), while
436 .search() checks throughout.
Darryl Greend5802922018-05-08 15:30:59 +0100437
Yuto Takano39639672021-08-05 19:47:48 +0100438 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100439 * include: A List of glob expressions to look for files through.
440 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100441
442 Returns a List of Match objects with identifiers.
Yuto Takano39639672021-08-05 19:47:48 +0100443 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100444 identifier_regex = re.compile(
445 # Match " something(a" or " *something(a". Functions.
446 # Assumptions:
447 # - function definition from return type to one of its arguments is
Yuto Takano55c6c872021-08-09 15:35:19 +0100448 # all on one line
Yuto Takanod93fa372021-08-06 23:05:55 +0100449 # - function definition line only contains alphanumeric, asterisk,
450 # underscore, and open bracket
451 r".* \**(\w+) *\( *\w|"
Yuto Takano55c6c872021-08-09 15:35:19 +0100452 # Match "(*something)(".
Yuto Takanod93fa372021-08-06 23:05:55 +0100453 r".*\( *\* *(\w+) *\) *\(|"
454 # Match names of named data structures.
455 r"(?:typedef +)?(?:struct|union|enum) +(\w+)(?: *{)?$|"
456 # Match names of typedef instances, after closing bracket.
Yuto Takanod70d4462021-08-09 12:45:51 +0100457 r"}? *(\w+)[;[].*"
458 )
459 exclusion_lines = re.compile(
460 r"^("
461 r"extern +\"C\"|"
462 r"(typedef +)?(struct|union|enum)( *{)?$|"
463 r"} *;?$|"
464 r"$|"
465 r"//|"
466 r"#"
467 r")"
468 )
Yuto Takanod93fa372021-08-06 23:05:55 +0100469
Yuto Takano50953432021-08-09 14:54:36 +0100470 files = self.get_files(include, exclude)
471 self.log.debug("Looking for identifiers in {} files".format(len(files)))
472
473 identifiers = []
474 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100475 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano39639672021-08-05 19:47:48 +0100476 in_block_comment = False
Yuto Takano55c6c872021-08-09 15:35:19 +0100477 # The previous line variable is used for concatenating lines
Yuto Takanod70d4462021-08-09 12:45:51 +0100478 # when identifiers are formatted and spread across multiple.
Yuto Takanod93fa372021-08-06 23:05:55 +0100479 previous_line = ""
Darryl Greend5802922018-05-08 15:30:59 +0100480
Yuto Takano8f457cf2021-08-06 17:54:58 +0100481 for line_no, line in enumerate(header):
Yuto Takano81528c02021-08-06 16:22:06 +0100482 # Skip parsing this line if a block comment ends on it,
483 # but don't skip if it has just started -- there is a chance
484 # it ends on the same line.
Yuto Takano39639672021-08-05 19:47:48 +0100485 if re.search(r"/\*", line):
Yuto Takano81528c02021-08-06 16:22:06 +0100486 in_block_comment = not in_block_comment
487 if re.search(r"\*/", line):
488 in_block_comment = not in_block_comment
Yuto Takano39639672021-08-05 19:47:48 +0100489 continue
490
Yuto Takano81528c02021-08-06 16:22:06 +0100491 if in_block_comment:
Yuto Takanod93fa372021-08-06 23:05:55 +0100492 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100493 continue
494
Yuto Takanod93fa372021-08-06 23:05:55 +0100495 if exclusion_lines.match(line):
496 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100497 continue
498
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100499 # If the line contains only space-separated alphanumeric
500 # characters (or underscore, asterisk, or, open bracket),
501 # and nothing else, high chance it's a declaration that
502 # continues on the next line
503 if re.match(r"^([\w\*\(]+\s+)+$", line):
Yuto Takanod93fa372021-08-06 23:05:55 +0100504 previous_line += line
Yuto Takano81528c02021-08-06 16:22:06 +0100505 continue
506
507 # If previous line seemed to start an unfinished declaration
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100508 # (as above), concat and treat them as one.
509 if previous_line:
510 line = previous_line.strip() + " " + line.strip()
Yuto Takanod93fa372021-08-06 23:05:55 +0100511 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100512
Yuto Takano8246eb82021-08-16 10:37:24 +0100513 # Skip parsing if line has a space in front = heuristic to
Yuto Takano81528c02021-08-06 16:22:06 +0100514 # skip function argument lines (highly subject to formatting
515 # changes)
516 if line[0] == " ":
Yuto Takano39639672021-08-05 19:47:48 +0100517 continue
Yuto Takano6f38ab32021-08-05 21:07:14 +0100518
Yuto Takanod93fa372021-08-06 23:05:55 +0100519 identifier = identifier_regex.search(line)
Yuto Takano39639672021-08-05 19:47:48 +0100520
Yuto Takanod70d4462021-08-09 12:45:51 +0100521 if not identifier:
522 continue
523
524 # Find the group that matched, and append it
525 for group in identifier.groups():
526 if not group:
527 continue
528
529 identifiers.append(Match(
530 header_file,
531 line,
532 (line_no, identifier.start(), identifier.end()),
533 group))
Yuto Takano39639672021-08-05 19:47:48 +0100534
535 return identifiers
536
537 def parse_symbols(self):
538 """
539 Compile the Mbed TLS libraries, and parse the TLS, Crypto, and x509
540 object files using nm to retrieve the list of referenced symbols.
Yuto Takano81528c02021-08-06 16:22:06 +0100541 Exceptions thrown here are rethrown because they would be critical
542 errors that void several tests, and thus needs to halt the program. This
543 is explicitly done for clarity.
Yuto Takano39639672021-08-05 19:47:48 +0100544
Yuto Takano81528c02021-08-06 16:22:06 +0100545 Returns a List of unique symbols defined and used in the libraries.
546 """
547 self.log.info("Compiling...")
Yuto Takano39639672021-08-05 19:47:48 +0100548 symbols = []
549
550 # Back up the config and atomically compile with the full configratuion.
Yuto Takanod70d4462021-08-09 12:45:51 +0100551 shutil.copy(
552 "include/mbedtls/mbedtls_config.h",
553 "include/mbedtls/mbedtls_config.h.bak"
554 )
Darryl Greend5802922018-05-08 15:30:59 +0100555 try:
Yuto Takano81528c02021-08-06 16:22:06 +0100556 # Use check=True in all subprocess calls so that failures are raised
557 # as exceptions and logged.
Yuto Takano39639672021-08-05 19:47:48 +0100558 subprocess.run(
Yuto Takano81528c02021-08-06 16:22:06 +0100559 ["python3", "scripts/config.py", "full"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100560 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100561 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100562 )
563 my_environment = os.environ.copy()
564 my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
Yuto Takano39639672021-08-05 19:47:48 +0100565 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100566 ["make", "clean", "lib"],
567 env=my_environment,
Yuto Takanobcc3d992021-08-06 23:14:58 +0100568 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100569 stdout=subprocess.PIPE,
Darryl Greend5802922018-05-08 15:30:59 +0100570 stderr=subprocess.STDOUT,
Yuto Takano39639672021-08-05 19:47:48 +0100571 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100572 )
Yuto Takano39639672021-08-05 19:47:48 +0100573
574 # Perform object file analysis using nm
Yuto Takanod70d4462021-08-09 12:45:51 +0100575 symbols = self.parse_symbols_from_nm([
576 "library/libmbedcrypto.a",
577 "library/libmbedtls.a",
578 "library/libmbedx509.a"
579 ])
Yuto Takano39639672021-08-05 19:47:48 +0100580
581 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100582 ["make", "clean"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100583 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100584 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100585 )
586 except subprocess.CalledProcessError as error:
Yuto Takano25eeb7b2021-08-06 21:27:59 +0100587 self.log.debug(error.output)
Yuto Takano81528c02021-08-06 16:22:06 +0100588 raise error
Yuto Takano39639672021-08-05 19:47:48 +0100589 finally:
Yuto Takano6fececf2021-08-07 17:28:23 +0100590 # Put back the original config regardless of there being errors.
591 # Works also for keyboard interrupts.
Yuto Takanod70d4462021-08-09 12:45:51 +0100592 shutil.move(
593 "include/mbedtls/mbedtls_config.h.bak",
594 "include/mbedtls/mbedtls_config.h"
595 )
Yuto Takano39639672021-08-05 19:47:48 +0100596
597 return symbols
598
599 def parse_symbols_from_nm(self, object_files):
600 """
601 Run nm to retrieve the list of referenced symbols in each object file.
602 Does not return the position data since it is of no use.
603
Yuto Takano81528c02021-08-06 16:22:06 +0100604 Args:
Yuto Takano55c6c872021-08-09 15:35:19 +0100605 * object_files: a List of compiled object filepaths to search through.
Yuto Takano81528c02021-08-06 16:22:06 +0100606
607 Returns a List of unique symbols defined and used in any of the object
608 files.
Yuto Takano39639672021-08-05 19:47:48 +0100609 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100610 nm_undefined_regex = re.compile(r"^\S+: +U |^$|^\S+:$")
611 nm_valid_regex = re.compile(r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)")
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100612 exclusions = ("FStar", "Hacl")
Yuto Takano39639672021-08-05 19:47:48 +0100613
614 symbols = []
615
Yuto Takano81528c02021-08-06 16:22:06 +0100616 # Gather all outputs of nm
Yuto Takano39639672021-08-05 19:47:48 +0100617 nm_output = ""
618 for lib in object_files:
619 nm_output += subprocess.run(
620 ["nm", "-og", lib],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100621 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100622 stdout=subprocess.PIPE,
623 stderr=subprocess.STDOUT,
624 check=True
625 ).stdout
Yuto Takano81528c02021-08-06 16:22:06 +0100626
Yuto Takano39639672021-08-05 19:47:48 +0100627 for line in nm_output.splitlines():
Yuto Takanod93fa372021-08-06 23:05:55 +0100628 if not nm_undefined_regex.match(line):
629 symbol = nm_valid_regex.match(line)
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100630 if (symbol and not symbol.group("symbol").startswith(exclusions)):
Yuto Takanoe77f6992021-08-05 20:22:59 +0100631 symbols.append(symbol.group("symbol"))
Yuto Takano39639672021-08-05 19:47:48 +0100632 else:
633 self.log.error(line)
Yuto Takano81528c02021-08-06 16:22:06 +0100634
Yuto Takano39639672021-08-05 19:47:48 +0100635 return symbols
636
Yuto Takano55c6c872021-08-09 15:35:19 +0100637class NameChecker():
638 """
639 Representation of the core name checking operation performed by this script.
640 """
641 def __init__(self, parse_result, log):
642 self.parse_result = parse_result
643 self.log = log
644
Yuto Takano55614b52021-08-07 01:00:18 +0100645 def perform_checks(self, quiet=False):
Yuto Takano39639672021-08-05 19:47:48 +0100646 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100647 A comprehensive checker that performs each check in order, and outputs
648 a final verdict.
Yuto Takano81528c02021-08-06 16:22:06 +0100649
650 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100651 * quiet: whether to hide detailed problem explanation.
Yuto Takano39639672021-08-05 19:47:48 +0100652 """
Yuto Takano81528c02021-08-06 16:22:06 +0100653 self.log.info("=============")
Yuto Takano39639672021-08-05 19:47:48 +0100654 problems = 0
Yuto Takano55614b52021-08-07 01:00:18 +0100655 problems += self.check_symbols_declared_in_header(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100656
Yuto Takanod70d4462021-08-09 12:45:51 +0100657 pattern_checks = [
658 ("macros", MACRO_PATTERN),
659 ("enum_consts", CONSTANTS_PATTERN),
660 ("identifiers", IDENTIFIER_PATTERN)
661 ]
Yuto Takano39639672021-08-05 19:47:48 +0100662 for group, check_pattern in pattern_checks:
Yuto Takano55614b52021-08-07 01:00:18 +0100663 problems += self.check_match_pattern(quiet, group, check_pattern)
Yuto Takano39639672021-08-05 19:47:48 +0100664
Yuto Takano55614b52021-08-07 01:00:18 +0100665 problems += self.check_for_typos(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100666
667 self.log.info("=============")
668 if problems > 0:
669 self.log.info("FAIL: {0} problem(s) to fix".format(str(problems)))
Yuto Takano55614b52021-08-07 01:00:18 +0100670 if quiet:
671 self.log.info("Remove --quiet to see explanations.")
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100672 else:
673 self.log.info("Use --quiet for minimal output.")
Yuto Takano55c6c872021-08-09 15:35:19 +0100674 return 1
Yuto Takano39639672021-08-05 19:47:48 +0100675 else:
676 self.log.info("PASS")
Yuto Takano55c6c872021-08-09 15:35:19 +0100677 return 0
Darryl Greend5802922018-05-08 15:30:59 +0100678
Yuto Takano55614b52021-08-07 01:00:18 +0100679 def check_symbols_declared_in_header(self, quiet):
Yuto Takano39639672021-08-05 19:47:48 +0100680 """
681 Perform a check that all detected symbols in the library object files
682 are properly declared in headers.
Yuto Takano977e07f2021-08-09 11:56:15 +0100683 Assumes parse_names_in_source() was called before this.
Darryl Greend5802922018-05-08 15:30:59 +0100684
Yuto Takano81528c02021-08-06 16:22:06 +0100685 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100686 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100687
688 Returns the number of problems that need fixing.
Yuto Takano39639672021-08-05 19:47:48 +0100689 """
690 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100691
Yuto Takano39639672021-08-05 19:47:48 +0100692 for symbol in self.parse_result["symbols"]:
693 found_symbol_declared = False
694 for identifier_match in self.parse_result["identifiers"]:
695 if symbol == identifier_match.name:
696 found_symbol_declared = True
697 break
Yuto Takano81528c02021-08-06 16:22:06 +0100698
Yuto Takano39639672021-08-05 19:47:48 +0100699 if not found_symbol_declared:
Yuto Takanod70d4462021-08-09 12:45:51 +0100700 problems.append(SymbolNotInHeader(symbol))
Yuto Takano39639672021-08-05 19:47:48 +0100701
Yuto Takanod70d4462021-08-09 12:45:51 +0100702 self.output_check_result(quiet, "All symbols in header", problems)
Yuto Takano39639672021-08-05 19:47:48 +0100703 return len(problems)
704
Yuto Takano55614b52021-08-07 01:00:18 +0100705 def check_match_pattern(self, quiet, group_to_check, check_pattern):
Yuto Takano81528c02021-08-06 16:22:06 +0100706 """
707 Perform a check that all items of a group conform to a regex pattern.
Yuto Takano977e07f2021-08-09 11:56:15 +0100708 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100709
710 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100711 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100712 * group_to_check: string key to index into self.parse_result.
713 * check_pattern: the regex to check against.
714
715 Returns the number of problems that need fixing.
716 """
Yuto Takano39639672021-08-05 19:47:48 +0100717 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100718
Yuto Takano39639672021-08-05 19:47:48 +0100719 for item_match in self.parse_result[group_to_check]:
720 if not re.match(check_pattern, item_match.name):
721 problems.append(PatternMismatch(check_pattern, item_match))
Yuto Takano201f9e82021-08-06 16:36:54 +0100722 # Double underscore is a reserved identifier, never to be used
Yuto Takanoc763cc32021-08-05 20:06:34 +0100723 if re.match(r".*__.*", item_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100724 problems.append(PatternMismatch("double underscore", item_match))
Yuto Takano81528c02021-08-06 16:22:06 +0100725
726 self.output_check_result(
Yuto Takanod70d4462021-08-09 12:45:51 +0100727 quiet,
Yuto Takano81528c02021-08-06 16:22:06 +0100728 "Naming patterns of {}".format(group_to_check),
Yuto Takano55614b52021-08-07 01:00:18 +0100729 problems)
Yuto Takano39639672021-08-05 19:47:48 +0100730 return len(problems)
Darryl Greend5802922018-05-08 15:30:59 +0100731
Yuto Takano55614b52021-08-07 01:00:18 +0100732 def check_for_typos(self, quiet):
Yuto Takano81528c02021-08-06 16:22:06 +0100733 """
734 Perform a check that all words in the soure code beginning with MBED are
735 either defined as macros, or as enum constants.
Yuto Takano977e07f2021-08-09 11:56:15 +0100736 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100737
738 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100739 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100740
741 Returns the number of problems that need fixing.
742 """
Yuto Takano39639672021-08-05 19:47:48 +0100743 problems = []
Yuto Takano39639672021-08-05 19:47:48 +0100744
Yuto Takanod70d4462021-08-09 12:45:51 +0100745 # Set comprehension, equivalent to a list comprehension wrapped by set()
Yuto Takanod93fa372021-08-06 23:05:55 +0100746 all_caps_names = {
747 match.name
748 for match
749 in self.parse_result["macros"] + self.parse_result["enum_consts"]}
750 typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$")
Yuto Takano39639672021-08-05 19:47:48 +0100751
Yuto Takanod93fa372021-08-06 23:05:55 +0100752 for name_match in self.parse_result["mbed_words"]:
Yuto Takano81528c02021-08-06 16:22:06 +0100753 found = name_match.name in all_caps_names
754
755 # Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
756 # PSA driver, they will not exist as macros. However, they
757 # should still be checked for typos using the equivalent
758 # BUILTINs that exist.
759 if "MBEDTLS_PSA_ACCEL_" in name_match.name:
760 found = name_match.name.replace(
761 "MBEDTLS_PSA_ACCEL_",
762 "MBEDTLS_PSA_BUILTIN_") in all_caps_names
763
Yuto Takanod93fa372021-08-06 23:05:55 +0100764 if not found and not typo_exclusion.search(name_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100765 problems.append(Typo(name_match))
Yuto Takano39639672021-08-05 19:47:48 +0100766
Yuto Takanod70d4462021-08-09 12:45:51 +0100767 self.output_check_result(quiet, "Likely typos", problems)
Yuto Takano81528c02021-08-06 16:22:06 +0100768 return len(problems)
769
Yuto Takanod70d4462021-08-09 12:45:51 +0100770 def output_check_result(self, quiet, name, problems):
Yuto Takano81528c02021-08-06 16:22:06 +0100771 """
772 Write out the PASS/FAIL status of a performed check depending on whether
773 there were problems.
Yuto Takanod70d4462021-08-09 12:45:51 +0100774
775 Args:
776 * quiet: whether to hide detailed problem explanation.
777 * name: the name of the test
778 * problems: a List of encountered Problems
Yuto Takano81528c02021-08-06 16:22:06 +0100779 """
Yuto Takano39639672021-08-05 19:47:48 +0100780 if problems:
Yuto Takano55614b52021-08-07 01:00:18 +0100781 self.log.info("{}: FAIL\n".format(name))
782 for problem in problems:
Yuto Takanod70d4462021-08-09 12:45:51 +0100783 problem.quiet = quiet
Yuto Takano55614b52021-08-07 01:00:18 +0100784 self.log.warning(str(problem))
Darryl Greend5802922018-05-08 15:30:59 +0100785 else:
Yuto Takano81528c02021-08-06 16:22:06 +0100786 self.log.info("{}: PASS".format(name))
Darryl Greend5802922018-05-08 15:30:59 +0100787
Yuto Takano39639672021-08-05 19:47:48 +0100788def main():
789 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100790 Perform argument parsing, and create an instance of CodeParser and
791 NameChecker to begin the core operation.
Yuto Takano39639672021-08-05 19:47:48 +0100792 """
Yuto Takanof005c332021-08-09 13:56:36 +0100793 parser = argparse.ArgumentParser(
Yuto Takano39639672021-08-05 19:47:48 +0100794 formatter_class=argparse.RawDescriptionHelpFormatter,
795 description=(
796 "This script confirms that the naming of all symbols and identifiers "
797 "in Mbed TLS are consistent with the house style and are also "
798 "self-consistent.\n\n"
Yuto Takanof005c332021-08-09 13:56:36 +0100799 "Expected to be run from the MbedTLS root directory.")
800 )
801 parser.add_argument(
802 "-v", "--verbose",
803 action="store_true",
804 help="show parse results"
805 )
806 parser.add_argument(
807 "-q", "--quiet",
808 action="store_true",
809 help="hide unnecessary text, explanations, and highlighs"
810 )
Darryl Greend5802922018-05-08 15:30:59 +0100811
Yuto Takanof005c332021-08-09 13:56:36 +0100812 args = parser.parse_args()
Darryl Greend5802922018-05-08 15:30:59 +0100813
Yuto Takano55c6c872021-08-09 15:35:19 +0100814 # Configure the global logger, which is then passed to the classes below
815 log = logging.getLogger()
816 log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
817 log.addHandler(logging.StreamHandler())
818
Darryl Greend5802922018-05-08 15:30:59 +0100819 try:
Yuto Takano55c6c872021-08-09 15:35:19 +0100820 code_parser = CodeParser(log)
821 parse_result = code_parser.comprehensive_parse()
Yuto Takanod93fa372021-08-06 23:05:55 +0100822 except Exception: # pylint: disable=broad-except
Darryl Greend5802922018-05-08 15:30:59 +0100823 traceback.print_exc()
824 sys.exit(2)
825
Yuto Takano55c6c872021-08-09 15:35:19 +0100826 name_checker = NameChecker(parse_result, log)
827 return_code = name_checker.perform_checks(quiet=args.quiet)
828
829 sys.exit(return_code)
830
Darryl Greend5802922018-05-08 15:30:59 +0100831if __name__ == "__main__":
Yuto Takano39639672021-08-05 19:47:48 +0100832 main()