blob: b12f406443093748d4bf479576d69a5c787fd64f [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 Takano9d9c6dc2021-08-16 10:43:45 +0100261 # Aligns the counts on the assumption that none exceeds 4 digits
262 self.log.debug(" {:4} Total Macros".format(len(all_macros)))
263 self.log.debug(" {:4} Non-identifier Macros".format(len(actual_macros)))
264 self.log.debug(" {:4} Enum Constants".format(len(enum_consts)))
265 self.log.debug(" {:4} Identifiers".format(len(identifiers)))
266 self.log.debug(" {:4} Exported Symbols".format(len(symbols)))
Yuto Takano55c6c872021-08-09 15:35:19 +0100267 return {
Yuto Takano81528c02021-08-06 16:22:06 +0100268 "macros": actual_macros,
269 "enum_consts": enum_consts,
270 "identifiers": identifiers,
271 "symbols": symbols,
Yuto Takanod93fa372021-08-06 23:05:55 +0100272 "mbed_words": mbed_words
Yuto Takano81528c02021-08-06 16:22:06 +0100273 }
274
Yuto Takano55c6c872021-08-09 15:35:19 +0100275 def get_files(self, include_wildcards, exclude_wildcards):
276 """
277 Get all files that match any of the UNIX-style wildcards. While the
278 check_names script is designed only for use on UNIX/macOS (due to nm),
279 this function alone would work fine on Windows even with forward slashes
280 in the wildcard.
281
282 Args:
283 * include_wildcards: a List of shell-style wildcards to match filepaths.
284 * exclude_wildcards: a List of shell-style wildcards to exclude.
285
286 Returns a List of relative filepaths.
287 """
288 accumulator = set()
289
290 # exclude_wildcards may be None. Also, consider the global exclusions.
291 exclude_wildcards = (exclude_wildcards or []) + self.excluded_files
292
293 # Perform set union on the glob results. Memoise individual sets.
294 for include_wildcard in include_wildcards:
295 if include_wildcard not in self.files:
296 self.files[include_wildcard] = set(glob.glob(
297 include_wildcard,
298 recursive=True
299 ))
300
301 accumulator = accumulator.union(self.files[include_wildcard])
302
303 # Perform set difference to exclude. Also use the same memo since their
304 # behaviour is pretty much identical and it can benefit from the cache.
305 for exclude_wildcard in exclude_wildcards:
306 if exclude_wildcard not in self.files:
307 self.files[exclude_wildcard] = set(glob.glob(
308 exclude_wildcard,
309 recursive=True
310 ))
311
312 accumulator = accumulator.difference(self.files[exclude_wildcard])
313
314 return list(accumulator)
315
Yuto Takano8e9a2192021-08-09 14:48:53 +0100316 def parse_macros(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100317 """
318 Parse all macros defined by #define preprocessor directives.
319
320 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100321 * include: A List of glob expressions to look for files through.
322 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100323
324 Returns a List of Match objects for the found macros.
Yuto Takano39639672021-08-05 19:47:48 +0100325 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100326 macro_regex = re.compile(r"# *define +(?P<macro>\w+)")
327 exclusions = (
Yuto Takano39639672021-08-05 19:47:48 +0100328 "asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
329 )
330
Yuto Takano50953432021-08-09 14:54:36 +0100331 files = self.get_files(include, exclude)
332 self.log.debug("Looking for macros in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100333
Yuto Takano50953432021-08-09 14:54:36 +0100334 macros = []
335 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100336 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100337 for line_no, line in enumerate(header):
Yuto Takanod93fa372021-08-06 23:05:55 +0100338 for macro in macro_regex.finditer(line):
Yuto Takanod70d4462021-08-09 12:45:51 +0100339 if macro.group("macro").startswith(exclusions):
340 continue
341
342 macros.append(Match(
343 header_file,
344 line,
345 (line_no, macro.start(), macro.end()),
346 macro.group("macro")))
Darryl Greend5802922018-05-08 15:30:59 +0100347
Yuto Takano39639672021-08-05 19:47:48 +0100348 return macros
Darryl Greend5802922018-05-08 15:30:59 +0100349
Yuto Takano8e9a2192021-08-09 14:48:53 +0100350 def parse_mbed_words(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100351 """
Yuto Takanob47b5042021-08-07 00:42:54 +0100352 Parse all words in the file that begin with MBED, in and out of macros,
353 comments, anything.
Yuto Takano39639672021-08-05 19:47:48 +0100354
355 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100356 * include: A List of glob expressions to look for files through.
357 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100358
359 Returns a List of Match objects for words beginning with MBED.
Yuto Takano39639672021-08-05 19:47:48 +0100360 """
Yuto Takanob47b5042021-08-07 00:42:54 +0100361 # Typos of TLS are common, hence the broader check below than MBEDTLS.
Yuto Takanod93fa372021-08-06 23:05:55 +0100362 mbed_regex = re.compile(r"\bMBED.+?_[A-Z0-9_]*")
363 exclusions = re.compile(r"// *no-check-names|#error")
364
Yuto Takano50953432021-08-09 14:54:36 +0100365 files = self.get_files(include, exclude)
366 self.log.debug("Looking for MBED words in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100367
Yuto Takano50953432021-08-09 14:54:36 +0100368 mbed_words = []
369 for filename in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100370 with open(filename, "r", encoding="utf-8") as fp:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100371 for line_no, line in enumerate(fp):
Yuto Takanod93fa372021-08-06 23:05:55 +0100372 if exclusions.search(line):
Yuto Takanoc62b4082021-08-05 20:17:07 +0100373 continue
Yuto Takano81528c02021-08-06 16:22:06 +0100374
Yuto Takanod93fa372021-08-06 23:05:55 +0100375 for name in mbed_regex.finditer(line):
376 mbed_words.append(Match(
Yuto Takano39639672021-08-05 19:47:48 +0100377 filename,
378 line,
Yuto Takanod93fa372021-08-06 23:05:55 +0100379 (line_no, name.start(), name.end()),
Yuto Takano39639672021-08-05 19:47:48 +0100380 name.group(0)
381 ))
382
Yuto Takanod93fa372021-08-06 23:05:55 +0100383 return mbed_words
Yuto Takano39639672021-08-05 19:47:48 +0100384
Yuto Takano8e9a2192021-08-09 14:48:53 +0100385 def parse_enum_consts(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100386 """
387 Parse all enum value constants that are declared.
388
389 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100390 * include: A List of glob expressions to look for files through.
391 * exclude: A List of glob expressions for excluding files.
Yuto Takano39639672021-08-05 19:47:48 +0100392
Yuto Takano81528c02021-08-06 16:22:06 +0100393 Returns a List of Match objects for the findings.
Yuto Takano39639672021-08-05 19:47:48 +0100394 """
Yuto Takano50953432021-08-09 14:54:36 +0100395 files = self.get_files(include, exclude)
396 self.log.debug("Looking for enum consts in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100397
Yuto Takano50953432021-08-09 14:54:36 +0100398 enum_consts = []
399 for header_file in files:
Yuto Takano39639672021-08-05 19:47:48 +0100400 # Emulate a finite state machine to parse enum declarations.
Yuto Takano81528c02021-08-06 16:22:06 +0100401 # 0 = not in enum
402 # 1 = inside enum
403 # 2 = almost inside enum
Darryl Greend5802922018-05-08 15:30:59 +0100404 state = 0
Yuto Takanoa083d152021-08-07 00:25:59 +0100405 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100406 for line_no, line in enumerate(header):
Yuto Takano13ecd992021-08-06 16:56:52 +0100407 # Match typedefs and brackets only when they are at the
408 # beginning of the line -- if they are indented, they might
409 # be sub-structures within structs, etc.
Yuto Takanod93fa372021-08-06 23:05:55 +0100410 if state == 0 and re.match(r"^(typedef +)?enum +{", line):
Darryl Greend5802922018-05-08 15:30:59 +0100411 state = 1
Yuto Takanod93fa372021-08-06 23:05:55 +0100412 elif state == 0 and re.match(r"^(typedef +)?enum", line):
Darryl Greend5802922018-05-08 15:30:59 +0100413 state = 2
Yuto Takanod93fa372021-08-06 23:05:55 +0100414 elif state == 2 and re.match(r"^{", line):
Darryl Greend5802922018-05-08 15:30:59 +0100415 state = 1
Yuto Takanod93fa372021-08-06 23:05:55 +0100416 elif state == 1 and re.match(r"^}", line):
Darryl Greend5802922018-05-08 15:30:59 +0100417 state = 0
Yuto Takanod93fa372021-08-06 23:05:55 +0100418 elif state == 1 and not re.match(r" *#", line):
Yuto Takano13ecd992021-08-06 16:56:52 +0100419 enum_const = re.match(r" *(?P<enum_const>\w+)", line)
Yuto Takanod70d4462021-08-09 12:45:51 +0100420 if not enum_const:
421 continue
422
423 enum_consts.append(Match(
424 header_file,
425 line,
426 (line_no, enum_const.start(), enum_const.end()),
427 enum_const.group("enum_const")))
Yuto Takano81528c02021-08-06 16:22:06 +0100428
Yuto Takano39639672021-08-05 19:47:48 +0100429 return enum_consts
Darryl Greend5802922018-05-08 15:30:59 +0100430
Yuto Takano8e9a2192021-08-09 14:48:53 +0100431 def parse_identifiers(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100432 """
Yuto Takano8246eb82021-08-16 10:37:24 +0100433 Parse all lines of a header where a function/enum/struct/union/typedef
434 identifier is declared, based on some heuristics. Highly dependent on
435 formatting style.
Yuto Takanod70d4462021-08-09 12:45:51 +0100436 Note: .match() checks at the beginning of the string (implicit ^), while
437 .search() checks throughout.
Darryl Greend5802922018-05-08 15:30:59 +0100438
Yuto Takano39639672021-08-05 19:47:48 +0100439 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100440 * include: A List of glob expressions to look for files through.
441 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100442
443 Returns a List of Match objects with identifiers.
Yuto Takano39639672021-08-05 19:47:48 +0100444 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100445 identifier_regex = re.compile(
446 # Match " something(a" or " *something(a". Functions.
447 # Assumptions:
448 # - function definition from return type to one of its arguments is
Yuto Takano55c6c872021-08-09 15:35:19 +0100449 # all on one line
Yuto Takanod93fa372021-08-06 23:05:55 +0100450 # - function definition line only contains alphanumeric, asterisk,
451 # underscore, and open bracket
452 r".* \**(\w+) *\( *\w|"
Yuto Takano55c6c872021-08-09 15:35:19 +0100453 # Match "(*something)(".
Yuto Takanod93fa372021-08-06 23:05:55 +0100454 r".*\( *\* *(\w+) *\) *\(|"
455 # Match names of named data structures.
456 r"(?:typedef +)?(?:struct|union|enum) +(\w+)(?: *{)?$|"
457 # Match names of typedef instances, after closing bracket.
Yuto Takanod70d4462021-08-09 12:45:51 +0100458 r"}? *(\w+)[;[].*"
459 )
460 exclusion_lines = re.compile(
461 r"^("
462 r"extern +\"C\"|"
463 r"(typedef +)?(struct|union|enum)( *{)?$|"
464 r"} *;?$|"
465 r"$|"
466 r"//|"
467 r"#"
468 r")"
469 )
Yuto Takanod93fa372021-08-06 23:05:55 +0100470
Yuto Takano50953432021-08-09 14:54:36 +0100471 files = self.get_files(include, exclude)
472 self.log.debug("Looking for identifiers in {} files".format(len(files)))
473
474 identifiers = []
475 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100476 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano39639672021-08-05 19:47:48 +0100477 in_block_comment = False
Yuto Takano55c6c872021-08-09 15:35:19 +0100478 # The previous line variable is used for concatenating lines
Yuto Takanod70d4462021-08-09 12:45:51 +0100479 # when identifiers are formatted and spread across multiple.
Yuto Takanod93fa372021-08-06 23:05:55 +0100480 previous_line = ""
Darryl Greend5802922018-05-08 15:30:59 +0100481
Yuto Takano8f457cf2021-08-06 17:54:58 +0100482 for line_no, line in enumerate(header):
Yuto Takano81528c02021-08-06 16:22:06 +0100483 # Skip parsing this line if a block comment ends on it,
484 # but don't skip if it has just started -- there is a chance
485 # it ends on the same line.
Yuto Takano39639672021-08-05 19:47:48 +0100486 if re.search(r"/\*", line):
Yuto Takano81528c02021-08-06 16:22:06 +0100487 in_block_comment = not in_block_comment
488 if re.search(r"\*/", line):
489 in_block_comment = not in_block_comment
Yuto Takano39639672021-08-05 19:47:48 +0100490 continue
491
Yuto Takano81528c02021-08-06 16:22:06 +0100492 if in_block_comment:
Yuto Takanod93fa372021-08-06 23:05:55 +0100493 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100494 continue
495
Yuto Takanod93fa372021-08-06 23:05:55 +0100496 if exclusion_lines.match(line):
497 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100498 continue
499
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100500 # If the line contains only space-separated alphanumeric
501 # characters (or underscore, asterisk, or, open bracket),
502 # and nothing else, high chance it's a declaration that
503 # continues on the next line
504 if re.match(r"^([\w\*\(]+\s+)+$", line):
Yuto Takanod93fa372021-08-06 23:05:55 +0100505 previous_line += line
Yuto Takano81528c02021-08-06 16:22:06 +0100506 continue
507
508 # If previous line seemed to start an unfinished declaration
Yuto Takanocfc9e4a2021-08-06 20:02:32 +0100509 # (as above), concat and treat them as one.
510 if previous_line:
511 line = previous_line.strip() + " " + line.strip()
Yuto Takanod93fa372021-08-06 23:05:55 +0100512 previous_line = ""
Yuto Takano81528c02021-08-06 16:22:06 +0100513
Yuto Takano8246eb82021-08-16 10:37:24 +0100514 # Skip parsing if line has a space in front = heuristic to
Yuto Takano81528c02021-08-06 16:22:06 +0100515 # skip function argument lines (highly subject to formatting
516 # changes)
517 if line[0] == " ":
Yuto Takano39639672021-08-05 19:47:48 +0100518 continue
Yuto Takano6f38ab32021-08-05 21:07:14 +0100519
Yuto Takanod93fa372021-08-06 23:05:55 +0100520 identifier = identifier_regex.search(line)
Yuto Takano39639672021-08-05 19:47:48 +0100521
Yuto Takanod70d4462021-08-09 12:45:51 +0100522 if not identifier:
523 continue
524
525 # Find the group that matched, and append it
526 for group in identifier.groups():
527 if not group:
528 continue
529
530 identifiers.append(Match(
531 header_file,
532 line,
533 (line_no, identifier.start(), identifier.end()),
534 group))
Yuto Takano39639672021-08-05 19:47:48 +0100535
536 return identifiers
537
538 def parse_symbols(self):
539 """
540 Compile the Mbed TLS libraries, and parse the TLS, Crypto, and x509
541 object files using nm to retrieve the list of referenced symbols.
Yuto Takano81528c02021-08-06 16:22:06 +0100542 Exceptions thrown here are rethrown because they would be critical
543 errors that void several tests, and thus needs to halt the program. This
544 is explicitly done for clarity.
Yuto Takano39639672021-08-05 19:47:48 +0100545
Yuto Takano81528c02021-08-06 16:22:06 +0100546 Returns a List of unique symbols defined and used in the libraries.
547 """
548 self.log.info("Compiling...")
Yuto Takano39639672021-08-05 19:47:48 +0100549 symbols = []
550
551 # Back up the config and atomically compile with the full configratuion.
Yuto Takanod70d4462021-08-09 12:45:51 +0100552 shutil.copy(
553 "include/mbedtls/mbedtls_config.h",
554 "include/mbedtls/mbedtls_config.h.bak"
555 )
Darryl Greend5802922018-05-08 15:30:59 +0100556 try:
Yuto Takano81528c02021-08-06 16:22:06 +0100557 # Use check=True in all subprocess calls so that failures are raised
558 # as exceptions and logged.
Yuto Takano39639672021-08-05 19:47:48 +0100559 subprocess.run(
Yuto Takano81528c02021-08-06 16:22:06 +0100560 ["python3", "scripts/config.py", "full"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100561 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100562 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100563 )
564 my_environment = os.environ.copy()
565 my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
Yuto Takano39639672021-08-05 19:47:48 +0100566 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100567 ["make", "clean", "lib"],
568 env=my_environment,
Yuto Takanobcc3d992021-08-06 23:14:58 +0100569 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100570 stdout=subprocess.PIPE,
Darryl Greend5802922018-05-08 15:30:59 +0100571 stderr=subprocess.STDOUT,
Yuto Takano39639672021-08-05 19:47:48 +0100572 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100573 )
Yuto Takano39639672021-08-05 19:47:48 +0100574
575 # Perform object file analysis using nm
Yuto Takanod70d4462021-08-09 12:45:51 +0100576 symbols = self.parse_symbols_from_nm([
577 "library/libmbedcrypto.a",
578 "library/libmbedtls.a",
579 "library/libmbedx509.a"
580 ])
Yuto Takano39639672021-08-05 19:47:48 +0100581
582 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100583 ["make", "clean"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100584 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100585 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100586 )
587 except subprocess.CalledProcessError as error:
Yuto Takano25eeb7b2021-08-06 21:27:59 +0100588 self.log.debug(error.output)
Yuto Takano81528c02021-08-06 16:22:06 +0100589 raise error
Yuto Takano39639672021-08-05 19:47:48 +0100590 finally:
Yuto Takano6fececf2021-08-07 17:28:23 +0100591 # Put back the original config regardless of there being errors.
592 # Works also for keyboard interrupts.
Yuto Takanod70d4462021-08-09 12:45:51 +0100593 shutil.move(
594 "include/mbedtls/mbedtls_config.h.bak",
595 "include/mbedtls/mbedtls_config.h"
596 )
Yuto Takano39639672021-08-05 19:47:48 +0100597
598 return symbols
599
600 def parse_symbols_from_nm(self, object_files):
601 """
602 Run nm to retrieve the list of referenced symbols in each object file.
603 Does not return the position data since it is of no use.
604
Yuto Takano81528c02021-08-06 16:22:06 +0100605 Args:
Yuto Takano55c6c872021-08-09 15:35:19 +0100606 * object_files: a List of compiled object filepaths to search through.
Yuto Takano81528c02021-08-06 16:22:06 +0100607
608 Returns a List of unique symbols defined and used in any of the object
609 files.
Yuto Takano39639672021-08-05 19:47:48 +0100610 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100611 nm_undefined_regex = re.compile(r"^\S+: +U |^$|^\S+:$")
612 nm_valid_regex = re.compile(r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)")
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100613 exclusions = ("FStar", "Hacl")
Yuto Takano39639672021-08-05 19:47:48 +0100614
615 symbols = []
616
Yuto Takano81528c02021-08-06 16:22:06 +0100617 # Gather all outputs of nm
Yuto Takano39639672021-08-05 19:47:48 +0100618 nm_output = ""
619 for lib in object_files:
620 nm_output += subprocess.run(
621 ["nm", "-og", lib],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100622 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100623 stdout=subprocess.PIPE,
624 stderr=subprocess.STDOUT,
625 check=True
626 ).stdout
Yuto Takano81528c02021-08-06 16:22:06 +0100627
Yuto Takano39639672021-08-05 19:47:48 +0100628 for line in nm_output.splitlines():
Yuto Takanod93fa372021-08-06 23:05:55 +0100629 if not nm_undefined_regex.match(line):
630 symbol = nm_valid_regex.match(line)
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100631 if (symbol and not symbol.group("symbol").startswith(exclusions)):
Yuto Takanoe77f6992021-08-05 20:22:59 +0100632 symbols.append(symbol.group("symbol"))
Yuto Takano39639672021-08-05 19:47:48 +0100633 else:
634 self.log.error(line)
Yuto Takano81528c02021-08-06 16:22:06 +0100635
Yuto Takano39639672021-08-05 19:47:48 +0100636 return symbols
637
Yuto Takano55c6c872021-08-09 15:35:19 +0100638class NameChecker():
639 """
640 Representation of the core name checking operation performed by this script.
641 """
642 def __init__(self, parse_result, log):
643 self.parse_result = parse_result
644 self.log = log
645
Yuto Takano55614b52021-08-07 01:00:18 +0100646 def perform_checks(self, quiet=False):
Yuto Takano39639672021-08-05 19:47:48 +0100647 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100648 A comprehensive checker that performs each check in order, and outputs
649 a final verdict.
Yuto Takano81528c02021-08-06 16:22:06 +0100650
651 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100652 * quiet: whether to hide detailed problem explanation.
Yuto Takano39639672021-08-05 19:47:48 +0100653 """
Yuto Takano81528c02021-08-06 16:22:06 +0100654 self.log.info("=============")
Yuto Takano39639672021-08-05 19:47:48 +0100655 problems = 0
Yuto Takano55614b52021-08-07 01:00:18 +0100656 problems += self.check_symbols_declared_in_header(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100657
Yuto Takanod70d4462021-08-09 12:45:51 +0100658 pattern_checks = [
659 ("macros", MACRO_PATTERN),
660 ("enum_consts", CONSTANTS_PATTERN),
661 ("identifiers", IDENTIFIER_PATTERN)
662 ]
Yuto Takano39639672021-08-05 19:47:48 +0100663 for group, check_pattern in pattern_checks:
Yuto Takano55614b52021-08-07 01:00:18 +0100664 problems += self.check_match_pattern(quiet, group, check_pattern)
Yuto Takano39639672021-08-05 19:47:48 +0100665
Yuto Takano55614b52021-08-07 01:00:18 +0100666 problems += self.check_for_typos(quiet)
Yuto Takano39639672021-08-05 19:47:48 +0100667
668 self.log.info("=============")
669 if problems > 0:
670 self.log.info("FAIL: {0} problem(s) to fix".format(str(problems)))
Yuto Takano55614b52021-08-07 01:00:18 +0100671 if quiet:
672 self.log.info("Remove --quiet to see explanations.")
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100673 else:
674 self.log.info("Use --quiet for minimal output.")
Yuto Takano55c6c872021-08-09 15:35:19 +0100675 return 1
Yuto Takano39639672021-08-05 19:47:48 +0100676 else:
677 self.log.info("PASS")
Yuto Takano55c6c872021-08-09 15:35:19 +0100678 return 0
Darryl Greend5802922018-05-08 15:30:59 +0100679
Yuto Takano55614b52021-08-07 01:00:18 +0100680 def check_symbols_declared_in_header(self, quiet):
Yuto Takano39639672021-08-05 19:47:48 +0100681 """
682 Perform a check that all detected symbols in the library object files
683 are properly declared in headers.
Yuto Takano977e07f2021-08-09 11:56:15 +0100684 Assumes parse_names_in_source() was called before this.
Darryl Greend5802922018-05-08 15:30:59 +0100685
Yuto Takano81528c02021-08-06 16:22:06 +0100686 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100687 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100688
689 Returns the number of problems that need fixing.
Yuto Takano39639672021-08-05 19:47:48 +0100690 """
691 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100692
Yuto Takano39639672021-08-05 19:47:48 +0100693 for symbol in self.parse_result["symbols"]:
694 found_symbol_declared = False
695 for identifier_match in self.parse_result["identifiers"]:
696 if symbol == identifier_match.name:
697 found_symbol_declared = True
698 break
Yuto Takano81528c02021-08-06 16:22:06 +0100699
Yuto Takano39639672021-08-05 19:47:48 +0100700 if not found_symbol_declared:
Yuto Takanod70d4462021-08-09 12:45:51 +0100701 problems.append(SymbolNotInHeader(symbol))
Yuto Takano39639672021-08-05 19:47:48 +0100702
Yuto Takanod70d4462021-08-09 12:45:51 +0100703 self.output_check_result(quiet, "All symbols in header", problems)
Yuto Takano39639672021-08-05 19:47:48 +0100704 return len(problems)
705
Yuto Takano55614b52021-08-07 01:00:18 +0100706 def check_match_pattern(self, quiet, group_to_check, check_pattern):
Yuto Takano81528c02021-08-06 16:22:06 +0100707 """
708 Perform a check that all items of a group conform to a regex pattern.
Yuto Takano977e07f2021-08-09 11:56:15 +0100709 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100710
711 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100712 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100713 * group_to_check: string key to index into self.parse_result.
714 * check_pattern: the regex to check against.
715
716 Returns the number of problems that need fixing.
717 """
Yuto Takano39639672021-08-05 19:47:48 +0100718 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100719
Yuto Takano39639672021-08-05 19:47:48 +0100720 for item_match in self.parse_result[group_to_check]:
721 if not re.match(check_pattern, item_match.name):
722 problems.append(PatternMismatch(check_pattern, item_match))
Yuto Takano201f9e82021-08-06 16:36:54 +0100723 # Double underscore is a reserved identifier, never to be used
Yuto Takanoc763cc32021-08-05 20:06:34 +0100724 if re.match(r".*__.*", item_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100725 problems.append(PatternMismatch("double underscore", item_match))
Yuto Takano81528c02021-08-06 16:22:06 +0100726
727 self.output_check_result(
Yuto Takanod70d4462021-08-09 12:45:51 +0100728 quiet,
Yuto Takano81528c02021-08-06 16:22:06 +0100729 "Naming patterns of {}".format(group_to_check),
Yuto Takano55614b52021-08-07 01:00:18 +0100730 problems)
Yuto Takano39639672021-08-05 19:47:48 +0100731 return len(problems)
Darryl Greend5802922018-05-08 15:30:59 +0100732
Yuto Takano55614b52021-08-07 01:00:18 +0100733 def check_for_typos(self, quiet):
Yuto Takano81528c02021-08-06 16:22:06 +0100734 """
735 Perform a check that all words in the soure code beginning with MBED are
736 either defined as macros, or as enum constants.
Yuto Takano977e07f2021-08-09 11:56:15 +0100737 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100738
739 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100740 * quiet: whether to hide detailed problem explanation.
Yuto Takano81528c02021-08-06 16:22:06 +0100741
742 Returns the number of problems that need fixing.
743 """
Yuto Takano39639672021-08-05 19:47:48 +0100744 problems = []
Yuto Takano39639672021-08-05 19:47:48 +0100745
Yuto Takanod70d4462021-08-09 12:45:51 +0100746 # Set comprehension, equivalent to a list comprehension wrapped by set()
Yuto Takanod93fa372021-08-06 23:05:55 +0100747 all_caps_names = {
748 match.name
749 for match
750 in self.parse_result["macros"] + self.parse_result["enum_consts"]}
751 typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$")
Yuto Takano39639672021-08-05 19:47:48 +0100752
Yuto Takanod93fa372021-08-06 23:05:55 +0100753 for name_match in self.parse_result["mbed_words"]:
Yuto Takano81528c02021-08-06 16:22:06 +0100754 found = name_match.name in all_caps_names
755
756 # Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
757 # PSA driver, they will not exist as macros. However, they
758 # should still be checked for typos using the equivalent
759 # BUILTINs that exist.
760 if "MBEDTLS_PSA_ACCEL_" in name_match.name:
761 found = name_match.name.replace(
762 "MBEDTLS_PSA_ACCEL_",
763 "MBEDTLS_PSA_BUILTIN_") in all_caps_names
764
Yuto Takanod93fa372021-08-06 23:05:55 +0100765 if not found and not typo_exclusion.search(name_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100766 problems.append(Typo(name_match))
Yuto Takano39639672021-08-05 19:47:48 +0100767
Yuto Takanod70d4462021-08-09 12:45:51 +0100768 self.output_check_result(quiet, "Likely typos", problems)
Yuto Takano81528c02021-08-06 16:22:06 +0100769 return len(problems)
770
Yuto Takanod70d4462021-08-09 12:45:51 +0100771 def output_check_result(self, quiet, name, problems):
Yuto Takano81528c02021-08-06 16:22:06 +0100772 """
773 Write out the PASS/FAIL status of a performed check depending on whether
774 there were problems.
Yuto Takanod70d4462021-08-09 12:45:51 +0100775
776 Args:
777 * quiet: whether to hide detailed problem explanation.
778 * name: the name of the test
779 * problems: a List of encountered Problems
Yuto Takano81528c02021-08-06 16:22:06 +0100780 """
Yuto Takano39639672021-08-05 19:47:48 +0100781 if problems:
Yuto Takano55614b52021-08-07 01:00:18 +0100782 self.log.info("{}: FAIL\n".format(name))
783 for problem in problems:
Yuto Takanod70d4462021-08-09 12:45:51 +0100784 problem.quiet = quiet
Yuto Takano55614b52021-08-07 01:00:18 +0100785 self.log.warning(str(problem))
Darryl Greend5802922018-05-08 15:30:59 +0100786 else:
Yuto Takano81528c02021-08-06 16:22:06 +0100787 self.log.info("{}: PASS".format(name))
Darryl Greend5802922018-05-08 15:30:59 +0100788
Yuto Takano39639672021-08-05 19:47:48 +0100789def main():
790 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100791 Perform argument parsing, and create an instance of CodeParser and
792 NameChecker to begin the core operation.
Yuto Takano39639672021-08-05 19:47:48 +0100793 """
Yuto Takanof005c332021-08-09 13:56:36 +0100794 parser = argparse.ArgumentParser(
Yuto Takano39639672021-08-05 19:47:48 +0100795 formatter_class=argparse.RawDescriptionHelpFormatter,
796 description=(
797 "This script confirms that the naming of all symbols and identifiers "
798 "in Mbed TLS are consistent with the house style and are also "
799 "self-consistent.\n\n"
Yuto Takanof005c332021-08-09 13:56:36 +0100800 "Expected to be run from the MbedTLS root directory.")
801 )
802 parser.add_argument(
803 "-v", "--verbose",
804 action="store_true",
805 help="show parse results"
806 )
807 parser.add_argument(
808 "-q", "--quiet",
809 action="store_true",
810 help="hide unnecessary text, explanations, and highlighs"
811 )
Darryl Greend5802922018-05-08 15:30:59 +0100812
Yuto Takanof005c332021-08-09 13:56:36 +0100813 args = parser.parse_args()
Darryl Greend5802922018-05-08 15:30:59 +0100814
Yuto Takano55c6c872021-08-09 15:35:19 +0100815 # Configure the global logger, which is then passed to the classes below
816 log = logging.getLogger()
817 log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
818 log.addHandler(logging.StreamHandler())
819
Darryl Greend5802922018-05-08 15:30:59 +0100820 try:
Yuto Takano55c6c872021-08-09 15:35:19 +0100821 code_parser = CodeParser(log)
822 parse_result = code_parser.comprehensive_parse()
Yuto Takanod93fa372021-08-06 23:05:55 +0100823 except Exception: # pylint: disable=broad-except
Darryl Greend5802922018-05-08 15:30:59 +0100824 traceback.print_exc()
825 sys.exit(2)
826
Yuto Takano55c6c872021-08-09 15:35:19 +0100827 name_checker = NameChecker(parse_result, log)
828 return_code = name_checker.perform_checks(quiet=args.quiet)
829
830 sys.exit(return_code)
831
Darryl Greend5802922018-05-08 15:30:59 +0100832if __name__ == "__main__":
Yuto Takano39639672021-08-05 19:47:48 +0100833 main()