blob: 5dc38fc52338c75653ee618157f7a6a776a2594a [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
42error error. 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 """
432 Parse all lines of a header where a function identifier is declared,
Yuto Takano81528c02021-08-06 16:22:06 +0100433 based on some huersitics. Highly dependent on formatting style.
Yuto Takanod70d4462021-08-09 12:45:51 +0100434 Note: .match() checks at the beginning of the string (implicit ^), while
435 .search() checks throughout.
Darryl Greend5802922018-05-08 15:30:59 +0100436
Yuto Takano39639672021-08-05 19:47:48 +0100437 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100438 * include: A List of glob expressions to look for files through.
439 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100440
441 Returns a List of Match objects with identifiers.
Yuto Takano39639672021-08-05 19:47:48 +0100442 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100443 identifier_regex = re.compile(
444 # Match " something(a" or " *something(a". Functions.
445 # Assumptions:
446 # - function definition from return type to one of its arguments is
Yuto Takano55c6c872021-08-09 15:35:19 +0100447 # all on one line
Yuto Takanod93fa372021-08-06 23:05:55 +0100448 # - function definition line only contains alphanumeric, asterisk,
449 # underscore, and open bracket
450 r".* \**(\w+) *\( *\w|"
Yuto Takano55c6c872021-08-09 15:35:19 +0100451 # Match "(*something)(".
Yuto Takanod93fa372021-08-06 23:05:55 +0100452 r".*\( *\* *(\w+) *\) *\(|"
453 # Match names of named data structures.
454 r"(?:typedef +)?(?:struct|union|enum) +(\w+)(?: *{)?$|"
455 # Match names of typedef instances, after closing bracket.
Yuto Takanod70d4462021-08-09 12:45:51 +0100456 r"}? *(\w+)[;[].*"
457 )
458 exclusion_lines = re.compile(
459 r"^("
460 r"extern +\"C\"|"
461 r"(typedef +)?(struct|union|enum)( *{)?$|"
462 r"} *;?$|"
463 r"$|"
464 r"//|"
465 r"#"
466 r")"
467 )
Yuto Takanod93fa372021-08-06 23:05:55 +0100468
Yuto Takano50953432021-08-09 14:54:36 +0100469 files = self.get_files(include, exclude)
470 self.log.debug("Looking for identifiers in {} files".format(len(files)))
471
472 identifiers = []
473 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100474 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano39639672021-08-05 19:47:48 +0100475 in_block_comment = False
Yuto Takano55c6c872021-08-09 15:35:19 +0100476 # The previous line variable is used for concatenating lines
Yuto Takanod70d4462021-08-09 12:45:51 +0100477 # when identifiers are formatted and spread across multiple.
Yuto Takanod93fa372021-08-06 23:05:55 +0100478 previous_line = ""
Darryl Greend5802922018-05-08 15:30:59 +0100479
Yuto Takano8f457cf2021-08-06 17:54:58 +0100480 for line_no, line in enumerate(header):
Yuto Takano81528c02021-08-06 16:22:06 +0100481 # Skip parsing this line if a block comment ends on it,
482 # but don't skip if it has just started -- there is a chance
483 # it ends on the same line.
Yuto Takano39639672021-08-05 19:47:48 +0100484 if re.search(r"/\*", line):
Yuto Takano81528c02021-08-06 16:22:06 +0100485 in_block_comment = not in_block_comment
486 if re.search(r"\*/", line):
487 in_block_comment = not in_block_comment
Yuto Takano39639672021-08-05 19:47:48 +0100488 continue
489
Yuto Takano81528c02021-08-06 16:22:06 +0100490 if in_block_comment:
Yuto Takanod93fa372021-08-06 23:05:55 +0100491 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100492 continue
493
Yuto Takanod93fa372021-08-06 23:05:55 +0100494 if exclusion_lines.match(line):
495 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100496 continue
497
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100498 # If the line contains only space-separated alphanumeric
499 # characters (or underscore, asterisk, or, open bracket),
500 # and nothing else, high chance it's a declaration that
501 # continues on the next line
502 if re.match(r"^([\w\*\(]+\s+)+$", line):
Yuto Takanod93fa372021-08-06 23:05:55 +0100503 previous_line += line
Yuto Takano81528c02021-08-06 16:22:06 +0100504 continue
505
506 # If previous line seemed to start an unfinished declaration
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100507 # (as above), concat and treat them as one.
508 if previous_line:
509 line = previous_line.strip() + " " + line.strip()
Yuto Takanod93fa372021-08-06 23:05:55 +0100510 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100511
512 # Skip parsing if line has a space in front = hueristic to
513 # skip function argument lines (highly subject to formatting
514 # changes)
515 if line[0] == " ":
Yuto Takano39639672021-08-05 19:47:48 +0100516 continue
Yuto Takano6f38ab32021-08-05 21:07:14 +0100517
Yuto Takanod93fa372021-08-06 23:05:55 +0100518 identifier = identifier_regex.search(line)
Yuto Takano39639672021-08-05 19:47:48 +0100519
Yuto Takanod70d4462021-08-09 12:45:51 +0100520 if not identifier:
521 continue
522
523 # Find the group that matched, and append it
524 for group in identifier.groups():
525 if not group:
526 continue
527
528 identifiers.append(Match(
529 header_file,
530 line,
531 (line_no, identifier.start(), identifier.end()),
532 group))
Yuto Takano39639672021-08-05 19:47:48 +0100533
534 return identifiers
535
536 def parse_symbols(self):
537 """
538 Compile the Mbed TLS libraries, and parse the TLS, Crypto, and x509
539 object files using nm to retrieve the list of referenced symbols.
Yuto Takano81528c02021-08-06 16:22:06 +0100540 Exceptions thrown here are rethrown because they would be critical
541 errors that void several tests, and thus needs to halt the program. This
542 is explicitly done for clarity.
Yuto Takano39639672021-08-05 19:47:48 +0100543
Yuto Takano81528c02021-08-06 16:22:06 +0100544 Returns a List of unique symbols defined and used in the libraries.
545 """
546 self.log.info("Compiling...")
Yuto Takano39639672021-08-05 19:47:48 +0100547 symbols = []
548
549 # Back up the config and atomically compile with the full configratuion.
Yuto Takanod70d4462021-08-09 12:45:51 +0100550 shutil.copy(
551 "include/mbedtls/mbedtls_config.h",
552 "include/mbedtls/mbedtls_config.h.bak"
553 )
Darryl Greend5802922018-05-08 15:30:59 +0100554 try:
Yuto Takano81528c02021-08-06 16:22:06 +0100555 # Use check=True in all subprocess calls so that failures are raised
556 # as exceptions and logged.
Yuto Takano39639672021-08-05 19:47:48 +0100557 subprocess.run(
Yuto Takano81528c02021-08-06 16:22:06 +0100558 ["python3", "scripts/config.py", "full"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100559 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100560 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100561 )
562 my_environment = os.environ.copy()
563 my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
Yuto Takano39639672021-08-05 19:47:48 +0100564 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100565 ["make", "clean", "lib"],
566 env=my_environment,
Yuto Takanobcc3d992021-08-06 23:14:58 +0100567 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100568 stdout=subprocess.PIPE,
Darryl Greend5802922018-05-08 15:30:59 +0100569 stderr=subprocess.STDOUT,
Yuto Takano39639672021-08-05 19:47:48 +0100570 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100571 )
Yuto Takano39639672021-08-05 19:47:48 +0100572
573 # Perform object file analysis using nm
Yuto Takanod70d4462021-08-09 12:45:51 +0100574 symbols = self.parse_symbols_from_nm([
575 "library/libmbedcrypto.a",
576 "library/libmbedtls.a",
577 "library/libmbedx509.a"
578 ])
Yuto Takano39639672021-08-05 19:47:48 +0100579
580 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100581 ["make", "clean"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100582 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100583 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100584 )
585 except subprocess.CalledProcessError as error:
Yuto Takano25eeb7b2021-08-06 21:27:59 +0100586 self.log.debug(error.output)
Yuto Takano81528c02021-08-06 16:22:06 +0100587 raise error
Yuto Takano39639672021-08-05 19:47:48 +0100588 finally:
Yuto Takano6fececf2021-08-07 17:28:23 +0100589 # Put back the original config regardless of there being errors.
590 # Works also for keyboard interrupts.
Yuto Takanod70d4462021-08-09 12:45:51 +0100591 shutil.move(
592 "include/mbedtls/mbedtls_config.h.bak",
593 "include/mbedtls/mbedtls_config.h"
594 )
Yuto Takano39639672021-08-05 19:47:48 +0100595
596 return symbols
597
598 def parse_symbols_from_nm(self, object_files):
599 """
600 Run nm to retrieve the list of referenced symbols in each object file.
601 Does not return the position data since it is of no use.
602
Yuto Takano81528c02021-08-06 16:22:06 +0100603 Args:
Yuto Takano55c6c872021-08-09 15:35:19 +0100604 * object_files: a List of compiled object filepaths to search through.
Yuto Takano81528c02021-08-06 16:22:06 +0100605
606 Returns a List of unique symbols defined and used in any of the object
607 files.
Yuto Takano39639672021-08-05 19:47:48 +0100608 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100609 nm_undefined_regex = re.compile(r"^\S+: +U |^$|^\S+:$")
610 nm_valid_regex = re.compile(r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)")
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100611 exclusions = ("FStar", "Hacl")
Yuto Takano39639672021-08-05 19:47:48 +0100612
613 symbols = []
614
Yuto Takano81528c02021-08-06 16:22:06 +0100615 # Gather all outputs of nm
Yuto Takano39639672021-08-05 19:47:48 +0100616 nm_output = ""
617 for lib in object_files:
618 nm_output += subprocess.run(
619 ["nm", "-og", lib],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100620 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100621 stdout=subprocess.PIPE,
622 stderr=subprocess.STDOUT,
623 check=True
624 ).stdout
Yuto Takano81528c02021-08-06 16:22:06 +0100625
Yuto Takano39639672021-08-05 19:47:48 +0100626 for line in nm_output.splitlines():
Yuto Takanod93fa372021-08-06 23:05:55 +0100627 if not nm_undefined_regex.match(line):
628 symbol = nm_valid_regex.match(line)
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100629 if (symbol and not symbol.group("symbol").startswith(exclusions)):
Yuto Takanoe77f6992021-08-05 20:22:59 +0100630 symbols.append(symbol.group("symbol"))
Yuto Takano39639672021-08-05 19:47:48 +0100631 else:
632 self.log.error(line)
Yuto Takano81528c02021-08-06 16:22:06 +0100633
Yuto Takano39639672021-08-05 19:47:48 +0100634 return symbols
635
Yuto Takano55c6c872021-08-09 15:35:19 +0100636class NameChecker():
637 """
638 Representation of the core name checking operation performed by this script.
639 """
640 def __init__(self, parse_result, log):
641 self.parse_result = parse_result
642 self.log = log
643
Yuto Takano55614b52021-08-07 01:00:18 +0100644 def perform_checks(self, quiet=False):
Yuto Takano39639672021-08-05 19:47:48 +0100645 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100646 A comprehensive checker that performs each check in order, and outputs
647 a final verdict.
Yuto Takano81528c02021-08-06 16:22:06 +0100648
649 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100650 * quiet: whether to hide detailed problem explanation.
Yuto Takano39639672021-08-05 19:47:48 +0100651 """
Yuto Takano81528c02021-08-06 16:22:06 +0100652 self.log.info("=============")
Yuto Takano39639672021-08-05 19:47:48 +0100653 problems = 0
Yuto Takano55614b52021-08-07 01:00:18 +0100654 problems += self.check_symbols_declared_in_header(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100655
Yuto Takanod70d4462021-08-09 12:45:51 +0100656 pattern_checks = [
657 ("macros", MACRO_PATTERN),
658 ("enum_consts", CONSTANTS_PATTERN),
659 ("identifiers", IDENTIFIER_PATTERN)
660 ]
Yuto Takano39639672021-08-05 19:47:48 +0100661 for group, check_pattern in pattern_checks:
Yuto Takano55614b52021-08-07 01:00:18 +0100662 problems += self.check_match_pattern(quiet, group, check_pattern)
Yuto Takano39639672021-08-05 19:47:48 +0100663
Yuto Takano55614b52021-08-07 01:00:18 +0100664 problems += self.check_for_typos(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100665
666 self.log.info("=============")
667 if problems > 0:
668 self.log.info("FAIL: {0} problem(s) to fix".format(str(problems)))
Yuto Takano55614b52021-08-07 01:00:18 +0100669 if quiet:
670 self.log.info("Remove --quiet to see explanations.")
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100671 else:
672 self.log.info("Use --quiet for minimal output.")
Yuto Takano55c6c872021-08-09 15:35:19 +0100673 return 1
Yuto Takano39639672021-08-05 19:47:48 +0100674 else:
675 self.log.info("PASS")
Yuto Takano55c6c872021-08-09 15:35:19 +0100676 return 0
Darryl Greend5802922018-05-08 15:30:59 +0100677
Yuto Takano55614b52021-08-07 01:00:18 +0100678 def check_symbols_declared_in_header(self, quiet):
Yuto Takano39639672021-08-05 19:47:48 +0100679 """
680 Perform a check that all detected symbols in the library object files
681 are properly declared in headers.
Yuto Takano977e07f2021-08-09 11:56:15 +0100682 Assumes parse_names_in_source() was called before this.
Darryl Greend5802922018-05-08 15:30:59 +0100683
Yuto Takano81528c02021-08-06 16:22:06 +0100684 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100685 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100686
687 Returns the number of problems that need fixing.
Yuto Takano39639672021-08-05 19:47:48 +0100688 """
689 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100690
Yuto Takano39639672021-08-05 19:47:48 +0100691 for symbol in self.parse_result["symbols"]:
692 found_symbol_declared = False
693 for identifier_match in self.parse_result["identifiers"]:
694 if symbol == identifier_match.name:
695 found_symbol_declared = True
696 break
Yuto Takano81528c02021-08-06 16:22:06 +0100697
Yuto Takano39639672021-08-05 19:47:48 +0100698 if not found_symbol_declared:
Yuto Takanod70d4462021-08-09 12:45:51 +0100699 problems.append(SymbolNotInHeader(symbol))
Yuto Takano39639672021-08-05 19:47:48 +0100700
Yuto Takanod70d4462021-08-09 12:45:51 +0100701 self.output_check_result(quiet, "All symbols in header", problems)
Yuto Takano39639672021-08-05 19:47:48 +0100702 return len(problems)
703
Yuto Takano55614b52021-08-07 01:00:18 +0100704 def check_match_pattern(self, quiet, group_to_check, check_pattern):
Yuto Takano81528c02021-08-06 16:22:06 +0100705 """
706 Perform a check that all items of a group conform to a regex pattern.
Yuto Takano977e07f2021-08-09 11:56:15 +0100707 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100708
709 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100710 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100711 * group_to_check: string key to index into self.parse_result.
712 * check_pattern: the regex to check against.
713
714 Returns the number of problems that need fixing.
715 """
Yuto Takano39639672021-08-05 19:47:48 +0100716 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100717
Yuto Takano39639672021-08-05 19:47:48 +0100718 for item_match in self.parse_result[group_to_check]:
719 if not re.match(check_pattern, item_match.name):
720 problems.append(PatternMismatch(check_pattern, item_match))
Yuto Takano201f9e82021-08-06 16:36:54 +0100721 # Double underscore is a reserved identifier, never to be used
Yuto Takanoc763cc32021-08-05 20:06:34 +0100722 if re.match(r".*__.*", item_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100723 problems.append(PatternMismatch("double underscore", item_match))
Yuto Takano81528c02021-08-06 16:22:06 +0100724
725 self.output_check_result(
Yuto Takanod70d4462021-08-09 12:45:51 +0100726 quiet,
Yuto Takano81528c02021-08-06 16:22:06 +0100727 "Naming patterns of {}".format(group_to_check),
Yuto Takano55614b52021-08-07 01:00:18 +0100728 problems)
Yuto Takano39639672021-08-05 19:47:48 +0100729 return len(problems)
Darryl Greend5802922018-05-08 15:30:59 +0100730
Yuto Takano55614b52021-08-07 01:00:18 +0100731 def check_for_typos(self, quiet):
Yuto Takano81528c02021-08-06 16:22:06 +0100732 """
733 Perform a check that all words in the soure code beginning with MBED are
734 either defined as macros, or as enum constants.
Yuto Takano977e07f2021-08-09 11:56:15 +0100735 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100736
737 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100738 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100739
740 Returns the number of problems that need fixing.
741 """
Yuto Takano39639672021-08-05 19:47:48 +0100742 problems = []
Yuto Takano39639672021-08-05 19:47:48 +0100743
Yuto Takanod70d4462021-08-09 12:45:51 +0100744 # Set comprehension, equivalent to a list comprehension wrapped by set()
Yuto Takanod93fa372021-08-06 23:05:55 +0100745 all_caps_names = {
746 match.name
747 for match
748 in self.parse_result["macros"] + self.parse_result["enum_consts"]}
749 typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$")
Yuto Takano39639672021-08-05 19:47:48 +0100750
Yuto Takanod93fa372021-08-06 23:05:55 +0100751 for name_match in self.parse_result["mbed_words"]:
Yuto Takano81528c02021-08-06 16:22:06 +0100752 found = name_match.name in all_caps_names
753
754 # Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
755 # PSA driver, they will not exist as macros. However, they
756 # should still be checked for typos using the equivalent
757 # BUILTINs that exist.
758 if "MBEDTLS_PSA_ACCEL_" in name_match.name:
759 found = name_match.name.replace(
760 "MBEDTLS_PSA_ACCEL_",
761 "MBEDTLS_PSA_BUILTIN_") in all_caps_names
762
Yuto Takanod93fa372021-08-06 23:05:55 +0100763 if not found and not typo_exclusion.search(name_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100764 problems.append(Typo(name_match))
Yuto Takano39639672021-08-05 19:47:48 +0100765
Yuto Takanod70d4462021-08-09 12:45:51 +0100766 self.output_check_result(quiet, "Likely typos", problems)
Yuto Takano81528c02021-08-06 16:22:06 +0100767 return len(problems)
768
Yuto Takanod70d4462021-08-09 12:45:51 +0100769 def output_check_result(self, quiet, name, problems):
Yuto Takano81528c02021-08-06 16:22:06 +0100770 """
771 Write out the PASS/FAIL status of a performed check depending on whether
772 there were problems.
Yuto Takanod70d4462021-08-09 12:45:51 +0100773
774 Args:
775 * quiet: whether to hide detailed problem explanation.
776 * name: the name of the test
777 * problems: a List of encountered Problems
Yuto Takano81528c02021-08-06 16:22:06 +0100778 """
Yuto Takano39639672021-08-05 19:47:48 +0100779 if problems:
Yuto Takano55614b52021-08-07 01:00:18 +0100780 self.log.info("{}: FAIL\n".format(name))
781 for problem in problems:
Yuto Takanod70d4462021-08-09 12:45:51 +0100782 problem.quiet = quiet
Yuto Takano55614b52021-08-07 01:00:18 +0100783 self.log.warning(str(problem))
Darryl Greend5802922018-05-08 15:30:59 +0100784 else:
Yuto Takano81528c02021-08-06 16:22:06 +0100785 self.log.info("{}: PASS".format(name))
Darryl Greend5802922018-05-08 15:30:59 +0100786
Yuto Takano39639672021-08-05 19:47:48 +0100787def main():
788 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100789 Perform argument parsing, and create an instance of CodeParser and
790 NameChecker to begin the core operation.
Yuto Takano39639672021-08-05 19:47:48 +0100791 """
Yuto Takanof005c332021-08-09 13:56:36 +0100792 parser = argparse.ArgumentParser(
Yuto Takano39639672021-08-05 19:47:48 +0100793 formatter_class=argparse.RawDescriptionHelpFormatter,
794 description=(
795 "This script confirms that the naming of all symbols and identifiers "
796 "in Mbed TLS are consistent with the house style and are also "
797 "self-consistent.\n\n"
Yuto Takanof005c332021-08-09 13:56:36 +0100798 "Expected to be run from the MbedTLS root directory.")
799 )
800 parser.add_argument(
801 "-v", "--verbose",
802 action="store_true",
803 help="show parse results"
804 )
805 parser.add_argument(
806 "-q", "--quiet",
807 action="store_true",
808 help="hide unnecessary text, explanations, and highlighs"
809 )
Darryl Greend5802922018-05-08 15:30:59 +0100810
Yuto Takanof005c332021-08-09 13:56:36 +0100811 args = parser.parse_args()
Darryl Greend5802922018-05-08 15:30:59 +0100812
Yuto Takano55c6c872021-08-09 15:35:19 +0100813 # Configure the global logger, which is then passed to the classes below
814 log = logging.getLogger()
815 log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
816 log.addHandler(logging.StreamHandler())
817
Darryl Greend5802922018-05-08 15:30:59 +0100818 try:
Yuto Takano55c6c872021-08-09 15:35:19 +0100819 code_parser = CodeParser(log)
820 parse_result = code_parser.comprehensive_parse()
Yuto Takanod93fa372021-08-06 23:05:55 +0100821 except Exception: # pylint: disable=broad-except
Darryl Greend5802922018-05-08 15:30:59 +0100822 traceback.print_exc()
823 sys.exit(2)
824
Yuto Takano55c6c872021-08-09 15:35:19 +0100825 name_checker = NameChecker(parse_result, log)
826 return_code = name_checker.perform_checks(quiet=args.quiet)
827
828 sys.exit(return_code)
829
Darryl Greend5802922018-05-08 15:30:59 +0100830if __name__ == "__main__":
Yuto Takano39639672021-08-05 19:47:48 +0100831 main()