blob: 7398f3c2d11f079c6ec6529eda67d12318c3384a [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.
Pengyu Lvcdac0d52022-11-08 15:55:00 +080039- Typo checking: All words that begin with MBED|PSA 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
Yuto Takanofc1e9ff2021-08-23 13:54:56 +010045import abc
Yuto Takano39639672021-08-05 19:47:48 +010046import argparse
Gilles Peskine89458d12021-09-27 19:20:17 +020047import fnmatch
Yuto Takano977e07f2021-08-09 11:56:15 +010048import glob
Yuto Takano39639672021-08-05 19:47:48 +010049import textwrap
Darryl Greend5802922018-05-08 15:30:59 +010050import os
51import sys
52import traceback
53import re
Yuto Takanob1417b42021-08-17 10:30:20 +010054import enum
Darryl Greend5802922018-05-08 15:30:59 +010055import shutil
56import subprocess
57import logging
58
Gilles Peskined9071e72022-09-18 21:17:09 +020059import scripts_path # pylint: disable=unused-import
60from mbedtls_dev import build_tree
61
62
Yuto Takano81528c02021-08-06 16:22:06 +010063# Naming patterns to check against. These are defined outside the NameCheck
64# class for ease of modification.
Janos Follath99387192022-08-10 11:11:34 +010065PUBLIC_MACRO_PATTERN = r"^(MBEDTLS|PSA)_[0-9A-Z_]*[0-9A-Z]$"
66INTERNAL_MACRO_PATTERN = r"^[0-9A-Za-z_]*[0-9A-Z]$"
67CONSTANTS_PATTERN = PUBLIC_MACRO_PATTERN
Yuto Takanoc1838932021-08-05 19:52:09 +010068IDENTIFIER_PATTERN = r"^(mbedtls|psa)_[0-9a-z_]*[0-9a-z]$"
Yuto Takano39639672021-08-05 19:47:48 +010069
Yuto Takanod93fa372021-08-06 23:05:55 +010070class Match(): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +010071 """
72 A class representing a match, together with its found position.
73
74 Fields:
75 * filename: the file that the match was in.
76 * line: the full line containing the match.
Yuto Takano704b0f72021-08-17 10:41:23 +010077 * line_no: the line number.
78 * pos: a tuple of (start, end) positions on the line where the match is.
Yuto Takano81528c02021-08-06 16:22:06 +010079 * name: the match itself.
80 """
Yuto Takano704b0f72021-08-17 10:41:23 +010081 def __init__(self, filename, line, line_no, pos, name):
82 # pylint: disable=too-many-arguments
Yuto Takano39639672021-08-05 19:47:48 +010083 self.filename = filename
84 self.line = line
Yuto Takano704b0f72021-08-17 10:41:23 +010085 self.line_no = line_no
Yuto Takano39639672021-08-05 19:47:48 +010086 self.pos = pos
87 self.name = name
Yuto Takano39639672021-08-05 19:47:48 +010088
Yuto Takanoa4e75122021-08-06 17:23:28 +010089 def __str__(self):
Yuto Takanofb86ac72021-08-16 10:32:40 +010090 """
91 Return a formatted code listing representation of the erroneous line.
92 """
Yuto Takano704b0f72021-08-17 10:41:23 +010093 gutter = format(self.line_no, "4d")
94 underline = self.pos[0] * " " + (self.pos[1] - self.pos[0]) * "^"
Yuto Takano381fda82021-08-06 23:37:20 +010095
Yuto Takanoa4e75122021-08-06 17:23:28 +010096 return (
Yuto Takanofb86ac72021-08-16 10:32:40 +010097 " {0} |\n".format(" " * len(gutter)) +
Yuto Takano381fda82021-08-06 23:37:20 +010098 " {0} | {1}".format(gutter, self.line) +
Yuto Takanofb86ac72021-08-16 10:32:40 +010099 " {0} | {1}\n".format(" " * len(gutter), underline)
Yuto Takanoa4e75122021-08-06 17:23:28 +0100100 )
Yuto Takanod93fa372021-08-06 23:05:55 +0100101
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100102class Problem(abc.ABC): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100103 """
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100104 An abstract parent class representing a form of static analysis error.
105 It extends an Abstract Base Class, which means it is not instantiable, and
106 it also mandates certain abstract methods to be implemented in subclasses.
Yuto Takano81528c02021-08-06 16:22:06 +0100107 """
Yuto Takano5473be22021-08-17 10:14:01 +0100108 # Class variable to control the quietness of all problems
109 quiet = False
Yuto Takano39639672021-08-05 19:47:48 +0100110 def __init__(self):
111 self.textwrapper = textwrap.TextWrapper()
Yuto Takano81528c02021-08-06 16:22:06 +0100112 self.textwrapper.width = 80
Yuto Takanoa4e75122021-08-06 17:23:28 +0100113 self.textwrapper.initial_indent = " > "
Yuto Takano81528c02021-08-06 16:22:06 +0100114 self.textwrapper.subsequent_indent = " "
Yuto Takano39639672021-08-05 19:47:48 +0100115
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100116 def __str__(self):
117 """
118 Unified string representation method for all Problems.
119 """
120 if self.__class__.quiet:
121 return self.quiet_output()
122 return self.verbose_output()
123
124 @abc.abstractmethod
125 def quiet_output(self):
126 """
127 The output when --quiet is enabled.
128 """
129 pass
130
131 @abc.abstractmethod
132 def verbose_output(self):
133 """
134 The default output with explanation and code snippet if appropriate.
135 """
136 pass
137
Yuto Takanod93fa372021-08-06 23:05:55 +0100138class SymbolNotInHeader(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100139 """
140 A problem that occurs when an exported/available symbol in the object file
141 is not explicitly declared in header files. Created with
142 NameCheck.check_symbols_declared_in_header()
143
144 Fields:
145 * symbol_name: the name of the symbol.
146 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100147 def __init__(self, symbol_name):
Yuto Takano39639672021-08-05 19:47:48 +0100148 self.symbol_name = symbol_name
149 Problem.__init__(self)
150
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100151 def quiet_output(self):
152 return "{0}".format(self.symbol_name)
Yuto Takano55614b52021-08-07 01:00:18 +0100153
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100154 def verbose_output(self):
Yuto Takano39639672021-08-05 19:47:48 +0100155 return self.textwrapper.fill(
156 "'{0}' was found as an available symbol in the output of nm, "
157 "however it was not declared in any header files."
158 .format(self.symbol_name))
159
Yuto Takanod93fa372021-08-06 23:05:55 +0100160class PatternMismatch(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100161 """
162 A problem that occurs when something doesn't match the expected pattern.
163 Created with NameCheck.check_match_pattern()
164
165 Fields:
166 * pattern: the expected regex pattern
167 * match: the Match object in question
168 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100169 def __init__(self, pattern, match):
Yuto Takano39639672021-08-05 19:47:48 +0100170 self.pattern = pattern
171 self.match = match
172 Problem.__init__(self)
Yuto Takano81528c02021-08-06 16:22:06 +0100173
Yuto Takano55614b52021-08-07 01:00:18 +0100174
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100175 def quiet_output(self):
176 return (
177 "{0}:{1}:{2}"
178 .format(self.match.filename, self.match.line_no, self.match.name)
179 )
180
181 def verbose_output(self):
Yuto Takano39639672021-08-05 19:47:48 +0100182 return self.textwrapper.fill(
Yuto Takanoa4e75122021-08-06 17:23:28 +0100183 "{0}:{1}: '{2}' does not match the required pattern '{3}'."
184 .format(
185 self.match.filename,
Yuto Takano5f831712021-08-18 18:03:24 +0100186 self.match.line_no,
Yuto Takanoa4e75122021-08-06 17:23:28 +0100187 self.match.name,
Yuto Takanod70d4462021-08-09 12:45:51 +0100188 self.pattern
189 )
190 ) + "\n" + str(self.match)
Yuto Takano39639672021-08-05 19:47:48 +0100191
Yuto Takanod93fa372021-08-06 23:05:55 +0100192class Typo(Problem): # pylint: disable=too-few-public-methods
Yuto Takano81528c02021-08-06 16:22:06 +0100193 """
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800194 A problem that occurs when a word using MBED or PSA doesn't
195 appear to be defined as constants nor enum values. Created with
196 NameCheck.check_for_typos()
Yuto Takano81528c02021-08-06 16:22:06 +0100197
198 Fields:
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800199 * match: the Match object of the MBED|PSA name in question.
Yuto Takano81528c02021-08-06 16:22:06 +0100200 """
Yuto Takanod70d4462021-08-09 12:45:51 +0100201 def __init__(self, match):
Yuto Takano39639672021-08-05 19:47:48 +0100202 self.match = match
203 Problem.__init__(self)
Yuto Takano81528c02021-08-06 16:22:06 +0100204
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100205 def quiet_output(self):
206 return (
207 "{0}:{1}:{2}"
208 .format(self.match.filename, self.match.line_no, self.match.name)
209 )
Yuto Takano55614b52021-08-07 01:00:18 +0100210
Yuto Takanofc1e9ff2021-08-23 13:54:56 +0100211 def verbose_output(self):
Yuto Takano39639672021-08-05 19:47:48 +0100212 return self.textwrapper.fill(
Yuto Takanoa4e75122021-08-06 17:23:28 +0100213 "{0}:{1}: '{2}' looks like a typo. It was not found in any "
214 "macros or any enums. If this is not a typo, put "
215 "//no-check-names after it."
Yuto Takano5f831712021-08-18 18:03:24 +0100216 .format(self.match.filename, self.match.line_no, self.match.name)
Yuto Takanod70d4462021-08-09 12:45:51 +0100217 ) + "\n" + str(self.match)
Darryl Greend5802922018-05-08 15:30:59 +0100218
Yuto Takano55c6c872021-08-09 15:35:19 +0100219class CodeParser():
Yuto Takano81528c02021-08-06 16:22:06 +0100220 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100221 Class for retrieving files and parsing the code. This can be used
222 independently of the checks that NameChecker performs, for example for
223 list_internal_identifiers.py.
Yuto Takano81528c02021-08-06 16:22:06 +0100224 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100225 def __init__(self, log):
226 self.log = log
Gilles Peskined9071e72022-09-18 21:17:09 +0200227 build_tree.check_repo_path()
Yuto Takano977e07f2021-08-09 11:56:15 +0100228
Yuto Takano8e9a2192021-08-09 14:48:53 +0100229 # Memo for storing "glob expression": set(filepaths)
230 self.files = {}
231
Gilles Peskine89458d12021-09-27 19:20:17 +0200232 # Globally excluded filenames.
233 # Note that "*" can match directory separators in exclude lists.
234 self.excluded_files = ["*/bn_mul", "*/compat-2.x.h"]
Yuto Takano977e07f2021-08-09 11:56:15 +0100235
Yuto Takano55c6c872021-08-09 15:35:19 +0100236 def comprehensive_parse(self):
Yuto Takano39639672021-08-05 19:47:48 +0100237 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100238 Comprehensive ("default") function to call each parsing function and
239 retrieve various elements of the code, together with the source location.
Darryl Greend5802922018-05-08 15:30:59 +0100240
Yuto Takano55c6c872021-08-09 15:35:19 +0100241 Returns a dict of parsed item key to the corresponding List of Matches.
Yuto Takano81528c02021-08-06 16:22:06 +0100242 """
243 self.log.info("Parsing source code...")
Yuto Takanod24e0372021-08-06 16:42:33 +0100244 self.log.debug(
Yuto Takano50953432021-08-09 14:54:36 +0100245 "The following files are excluded from the search: {}"
Yuto Takanod24e0372021-08-06 16:42:33 +0100246 .format(str(self.excluded_files))
247 )
Yuto Takano81528c02021-08-06 16:22:06 +0100248
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800249 all_macros = {"public": [], "internal": [], "private":[]}
Janos Follath99387192022-08-10 11:11:34 +0100250 all_macros["public"] = self.parse_macros([
Yuto Takano8e9a2192021-08-09 14:48:53 +0100251 "include/mbedtls/*.h",
252 "include/psa/*.h",
Yuto Takanod70d4462021-08-09 12:45:51 +0100253 "3rdparty/everest/include/everest/everest.h",
254 "3rdparty/everest/include/everest/x25519.h"
Yuto Takano8e9a2192021-08-09 14:48:53 +0100255 ])
Janos Follath99387192022-08-10 11:11:34 +0100256 all_macros["internal"] = self.parse_macros([
257 "library/*.h",
258 "tests/include/test/drivers/*.h",
259 ])
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800260 all_macros["private"] = self.parse_macros([
261 "library/*.c",
262 ])
Yuto Takano8e9a2192021-08-09 14:48:53 +0100263 enum_consts = self.parse_enum_consts([
264 "include/mbedtls/*.h",
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800265 "include/psa/*.h",
Yuto Takano8e9a2192021-08-09 14:48:53 +0100266 "library/*.h",
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800267 "library/*.c",
Yuto Takano8e9a2192021-08-09 14:48:53 +0100268 "3rdparty/everest/include/everest/everest.h",
269 "3rdparty/everest/include/everest/x25519.h"
270 ])
271 identifiers = self.parse_identifiers([
272 "include/mbedtls/*.h",
273 "include/psa/*.h",
274 "library/*.h",
275 "3rdparty/everest/include/everest/everest.h",
276 "3rdparty/everest/include/everest/x25519.h"
277 ])
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800278 mbed_psa_words = self.parse_mbed_psa_words([
Yuto Takano8e9a2192021-08-09 14:48:53 +0100279 "include/mbedtls/*.h",
280 "include/psa/*.h",
281 "library/*.h",
282 "3rdparty/everest/include/everest/everest.h",
283 "3rdparty/everest/include/everest/x25519.h",
284 "library/*.c",
Yuto Takano81528c02021-08-06 16:22:06 +0100285 "3rdparty/everest/library/everest.c",
Yuto Takanod70d4462021-08-09 12:45:51 +0100286 "3rdparty/everest/library/x25519.c"
Archana634e0d22022-01-10 17:37:42 +0530287 ], ["library/psa_crypto_driver_wrappers.c"])
Yuto Takano81528c02021-08-06 16:22:06 +0100288 symbols = self.parse_symbols()
289
290 # Remove identifier macros like mbedtls_printf or mbedtls_calloc
291 identifiers_justname = [x.name for x in identifiers]
Janos Follath99387192022-08-10 11:11:34 +0100292 actual_macros = {"public": [], "internal": []}
293 for scope in actual_macros:
294 for macro in all_macros[scope]:
295 if macro.name not in identifiers_justname:
296 actual_macros[scope].append(macro)
Yuto Takano81528c02021-08-06 16:22:06 +0100297
298 self.log.debug("Found:")
Yuto Takano9d9c6dc2021-08-16 10:43:45 +0100299 # Aligns the counts on the assumption that none exceeds 4 digits
Janos Follath99387192022-08-10 11:11:34 +0100300 for scope in actual_macros:
301 self.log.debug(" {:4} Total {} Macros"
Janos Follath8d59c862022-08-10 15:35:35 +0100302 .format(len(all_macros[scope]), scope))
Janos Follath99387192022-08-10 11:11:34 +0100303 self.log.debug(" {:4} {} Non-identifier Macros"
Janos Follath8d59c862022-08-10 15:35:35 +0100304 .format(len(actual_macros[scope]), scope))
Yuto Takano9d9c6dc2021-08-16 10:43:45 +0100305 self.log.debug(" {:4} Enum Constants".format(len(enum_consts)))
306 self.log.debug(" {:4} Identifiers".format(len(identifiers)))
307 self.log.debug(" {:4} Exported Symbols".format(len(symbols)))
Yuto Takano55c6c872021-08-09 15:35:19 +0100308 return {
Janos Follath99387192022-08-10 11:11:34 +0100309 "public_macros": actual_macros["public"],
310 "internal_macros": actual_macros["internal"],
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800311 "private_macros": all_macros["private"],
Yuto Takano81528c02021-08-06 16:22:06 +0100312 "enum_consts": enum_consts,
313 "identifiers": identifiers,
314 "symbols": symbols,
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800315 "mbed_psa_words": mbed_psa_words
Yuto Takano81528c02021-08-06 16:22:06 +0100316 }
317
Gilles Peskine89458d12021-09-27 19:20:17 +0200318 def is_file_excluded(self, path, exclude_wildcards):
Gilles Peskine8a832242021-09-28 10:12:49 +0200319 """Whether the given file path is excluded."""
Gilles Peskine89458d12021-09-27 19:20:17 +0200320 # exclude_wildcards may be None. Also, consider the global exclusions.
321 exclude_wildcards = (exclude_wildcards or []) + self.excluded_files
322 for pattern in exclude_wildcards:
323 if fnmatch.fnmatch(path, pattern):
324 return True
325 return False
326
Yuto Takano55c6c872021-08-09 15:35:19 +0100327 def get_files(self, include_wildcards, exclude_wildcards):
328 """
329 Get all files that match any of the UNIX-style wildcards. While the
330 check_names script is designed only for use on UNIX/macOS (due to nm),
331 this function alone would work fine on Windows even with forward slashes
332 in the wildcard.
333
334 Args:
335 * include_wildcards: a List of shell-style wildcards to match filepaths.
336 * exclude_wildcards: a List of shell-style wildcards to exclude.
337
338 Returns a List of relative filepaths.
339 """
340 accumulator = set()
341
Yuto Takano55c6c872021-08-09 15:35:19 +0100342 for include_wildcard in include_wildcards:
Gilles Peskine89458d12021-09-27 19:20:17 +0200343 accumulator = accumulator.union(glob.iglob(include_wildcard))
Yuto Takano55c6c872021-08-09 15:35:19 +0100344
Gilles Peskine89458d12021-09-27 19:20:17 +0200345 return list(path for path in accumulator
346 if not self.is_file_excluded(path, exclude_wildcards))
Yuto Takano55c6c872021-08-09 15:35:19 +0100347
Yuto Takano8e9a2192021-08-09 14:48:53 +0100348 def parse_macros(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100349 """
350 Parse all macros defined by #define preprocessor directives.
351
352 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100353 * include: A List of glob expressions to look for files through.
354 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100355
356 Returns a List of Match objects for the found macros.
Yuto Takano39639672021-08-05 19:47:48 +0100357 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100358 macro_regex = re.compile(r"# *define +(?P<macro>\w+)")
359 exclusions = (
Yuto Takano39639672021-08-05 19:47:48 +0100360 "asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
361 )
362
Yuto Takano50953432021-08-09 14:54:36 +0100363 files = self.get_files(include, exclude)
364 self.log.debug("Looking for macros in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100365
Yuto Takano50953432021-08-09 14:54:36 +0100366 macros = []
367 for header_file in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100368 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100369 for line_no, line in enumerate(header):
Yuto Takanod93fa372021-08-06 23:05:55 +0100370 for macro in macro_regex.finditer(line):
Yuto Takanod70d4462021-08-09 12:45:51 +0100371 if macro.group("macro").startswith(exclusions):
372 continue
373
374 macros.append(Match(
375 header_file,
376 line,
Yuto Takano704b0f72021-08-17 10:41:23 +0100377 line_no,
378 macro.span("macro"),
Yuto Takanod70d4462021-08-09 12:45:51 +0100379 macro.group("macro")))
Darryl Greend5802922018-05-08 15:30:59 +0100380
Yuto Takano39639672021-08-05 19:47:48 +0100381 return macros
Darryl Greend5802922018-05-08 15:30:59 +0100382
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800383 def parse_mbed_psa_words(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100384 """
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800385 Parse all words in the file that begin with MBED|PSA, in and out of
386 macros, comments, anything.
Yuto Takano39639672021-08-05 19:47:48 +0100387
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 Takano81528c02021-08-06 16:22:06 +0100391
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800392 Returns a List of Match objects for words beginning with MBED|PSA.
Yuto Takano39639672021-08-05 19:47:48 +0100393 """
Yuto Takanob47b5042021-08-07 00:42:54 +0100394 # Typos of TLS are common, hence the broader check below than MBEDTLS.
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800395 mbed_regex = re.compile(r"\b(MBED.+?|PSA)_[A-Z0-9_]*")
Yuto Takanod93fa372021-08-06 23:05:55 +0100396 exclusions = re.compile(r"// *no-check-names|#error")
397
Yuto Takano50953432021-08-09 14:54:36 +0100398 files = self.get_files(include, exclude)
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800399 self.log.debug(
400 "Looking for MBED|PSA words in {} files"
401 .format(len(files))
402 )
Yuto Takanod93fa372021-08-06 23:05:55 +0100403
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800404 mbed_psa_words = []
Yuto Takano50953432021-08-09 14:54:36 +0100405 for filename in files:
Yuto Takanoa083d152021-08-07 00:25:59 +0100406 with open(filename, "r", encoding="utf-8") as fp:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100407 for line_no, line in enumerate(fp):
Yuto Takanod93fa372021-08-06 23:05:55 +0100408 if exclusions.search(line):
Yuto Takanoc62b4082021-08-05 20:17:07 +0100409 continue
Yuto Takano81528c02021-08-06 16:22:06 +0100410
Yuto Takanod93fa372021-08-06 23:05:55 +0100411 for name in mbed_regex.finditer(line):
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800412 mbed_psa_words.append(Match(
Yuto Takano39639672021-08-05 19:47:48 +0100413 filename,
414 line,
Yuto Takano704b0f72021-08-17 10:41:23 +0100415 line_no,
416 name.span(0),
417 name.group(0)))
Yuto Takano39639672021-08-05 19:47:48 +0100418
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800419 return mbed_psa_words
Yuto Takano39639672021-08-05 19:47:48 +0100420
Yuto Takano8e9a2192021-08-09 14:48:53 +0100421 def parse_enum_consts(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100422 """
423 Parse all enum value constants that are declared.
424
425 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100426 * include: A List of glob expressions to look for files through.
427 * exclude: A List of glob expressions for excluding files.
Yuto Takano39639672021-08-05 19:47:48 +0100428
Yuto Takano81528c02021-08-06 16:22:06 +0100429 Returns a List of Match objects for the findings.
Yuto Takano39639672021-08-05 19:47:48 +0100430 """
Yuto Takano50953432021-08-09 14:54:36 +0100431 files = self.get_files(include, exclude)
432 self.log.debug("Looking for enum consts in {} files".format(len(files)))
Yuto Takanod93fa372021-08-06 23:05:55 +0100433
Yuto Takanob1417b42021-08-17 10:30:20 +0100434 # Emulate a finite state machine to parse enum declarations.
435 # OUTSIDE_KEYWORD = outside the enum keyword
436 # IN_BRACES = inside enum opening braces
437 # IN_BETWEEN = between enum keyword and opening braces
438 states = enum.Enum("FSM", ["OUTSIDE_KEYWORD", "IN_BRACES", "IN_BETWEEN"])
Yuto Takano50953432021-08-09 14:54:36 +0100439 enum_consts = []
440 for header_file in files:
Yuto Takanob1417b42021-08-17 10:30:20 +0100441 state = states.OUTSIDE_KEYWORD
Yuto Takanoa083d152021-08-07 00:25:59 +0100442 with open(header_file, "r", encoding="utf-8") as header:
Yuto Takano8f457cf2021-08-06 17:54:58 +0100443 for line_no, line in enumerate(header):
Yuto Takano13ecd992021-08-06 16:56:52 +0100444 # Match typedefs and brackets only when they are at the
445 # beginning of the line -- if they are indented, they might
446 # be sub-structures within structs, etc.
David Horstmannf91090e2022-12-16 13:39:04 +0000447 optional_c_identifier = r"([_a-zA-Z][_a-zA-Z0-9]*)?"
Yuto Takanob1417b42021-08-17 10:30:20 +0100448 if (state == states.OUTSIDE_KEYWORD and
David Horstmannf91090e2022-12-16 13:39:04 +0000449 re.search(r"^(typedef +)?enum " + \
450 optional_c_identifier + \
451 r" *{", line)):
Yuto Takanob1417b42021-08-17 10:30:20 +0100452 state = states.IN_BRACES
453 elif (state == states.OUTSIDE_KEYWORD and
454 re.search(r"^(typedef +)?enum", line)):
455 state = states.IN_BETWEEN
456 elif (state == states.IN_BETWEEN and
457 re.search(r"^{", line)):
458 state = states.IN_BRACES
459 elif (state == states.IN_BRACES and
460 re.search(r"^}", line)):
461 state = states.OUTSIDE_KEYWORD
462 elif (state == states.IN_BRACES and
463 not re.search(r"^ *#", line)):
Yuto Takano90bc0262021-08-16 11:34:10 +0100464 enum_const = re.search(r"^ *(?P<enum_const>\w+)", line)
Yuto Takanod70d4462021-08-09 12:45:51 +0100465 if not enum_const:
466 continue
467
468 enum_consts.append(Match(
469 header_file,
470 line,
Yuto Takano704b0f72021-08-17 10:41:23 +0100471 line_no,
472 enum_const.span("enum_const"),
Yuto Takanod70d4462021-08-09 12:45:51 +0100473 enum_const.group("enum_const")))
Yuto Takano81528c02021-08-06 16:22:06 +0100474
Yuto Takano39639672021-08-05 19:47:48 +0100475 return enum_consts
Darryl Greend5802922018-05-08 15:30:59 +0100476
Gilles Peskineb4b18c12021-11-17 20:43:35 +0100477 IGNORED_CHUNK_REGEX = re.compile('|'.join([
478 r'/\*.*?\*/', # block comment entirely on one line
479 r'//.*', # line comment
480 r'(?P<string>")(?:[^\\\"]|\\.)*"', # string literal
481 ]))
482
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100483 def strip_comments_and_literals(self, line, in_block_comment):
484 """Strip comments and string literals from line.
485
486 Continuation lines are not supported.
487
488 If in_block_comment is true, assume that the line starts inside a
489 block comment.
490
491 Return updated values of (line, in_block_comment) where:
492 * Comments in line have been replaced by a space (or nothing at the
493 start or end of the line).
494 * String contents have been removed.
495 * in_block_comment indicates whether the line ends inside a block
496 comment that continues on the next line.
497 """
Gilles Peskinef303c0d2021-11-17 20:45:39 +0100498
499 # Terminate current multiline comment?
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100500 if in_block_comment:
Gilles Peskinef303c0d2021-11-17 20:45:39 +0100501 m = re.search(r"\*/", line)
502 if m:
503 in_block_comment = False
504 line = line[m.end(0):]
505 else:
506 return '', True
Gilles Peskineb4b18c12021-11-17 20:43:35 +0100507
508 # Remove full comments and string literals.
509 # Do it all together to handle cases like "/*" correctly.
510 # Note that continuation lines are not supported.
511 line = re.sub(self.IGNORED_CHUNK_REGEX,
512 lambda s: '""' if s.group('string') else ' ',
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100513 line)
Gilles Peskineb4b18c12021-11-17 20:43:35 +0100514
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100515 # Start an unfinished comment?
Gilles Peskineb4b18c12021-11-17 20:43:35 +0100516 # (If `/*` was part of a complete comment, it's already been removed.)
Gilles Peskinef303c0d2021-11-17 20:45:39 +0100517 m = re.search(r"/\*", line)
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100518 if m:
519 in_block_comment = True
Gilles Peskinef303c0d2021-11-17 20:45:39 +0100520 line = line[:m.start(0)]
Gilles Peskineb4b18c12021-11-17 20:43:35 +0100521
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100522 return line, in_block_comment
523
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100524 IDENTIFIER_REGEX = re.compile('|'.join([
Gilles Peskine152de232021-11-16 20:56:47 +0100525 # Match " something(a" or " *something(a". Functions.
526 # Assumptions:
527 # - function definition from return type to one of its arguments is
528 # all on one line
529 # - function definition line only contains alphanumeric, asterisk,
530 # underscore, and open bracket
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100531 r".* \**(\w+) *\( *\w",
Gilles Peskine152de232021-11-16 20:56:47 +0100532 # Match "(*something)(".
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100533 r".*\( *\* *(\w+) *\) *\(",
Gilles Peskine152de232021-11-16 20:56:47 +0100534 # Match names of named data structures.
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100535 r"(?:typedef +)?(?:struct|union|enum) +(\w+)(?: *{)?$",
Gilles Peskine152de232021-11-16 20:56:47 +0100536 # Match names of typedef instances, after closing bracket.
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100537 r"}? *(\w+)[;[].*",
538 ]))
Gilles Peskine152de232021-11-16 20:56:47 +0100539 # The regex below is indented for clarity.
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100540 EXCLUSION_LINES = re.compile("|".join([
541 r"extern +\"C\"",
542 r"(typedef +)?(struct|union|enum)( *{)?$",
543 r"} *;?$",
544 r"$",
545 r"//",
546 r"#",
547 ]))
Gilles Peskine152de232021-11-16 20:56:47 +0100548
549 def parse_identifiers_in_file(self, header_file, identifiers):
550 """
551 Parse all lines of a header where a function/enum/struct/union/typedef
552 identifier is declared, based on some regex and heuristics. Highly
553 dependent on formatting style.
554
555 Append found matches to the list ``identifiers``.
556 """
557
558 with open(header_file, "r", encoding="utf-8") as header:
559 in_block_comment = False
560 # The previous line variable is used for concatenating lines
561 # when identifiers are formatted and spread across multiple
562 # lines.
563 previous_line = ""
564
565 for line_no, line in enumerate(header):
Gilles Peskineb9fc4882021-11-17 20:32:31 +0100566 line, in_block_comment = \
567 self.strip_comments_and_literals(line, in_block_comment)
Gilles Peskine152de232021-11-16 20:56:47 +0100568
Gilles Peskine9b2fa722021-11-17 20:23:18 +0100569 if self.EXCLUSION_LINES.match(line):
Gilles Peskine152de232021-11-16 20:56:47 +0100570 previous_line = ""
571 continue
572
573 # If the line contains only space-separated alphanumeric
Gilles Peskinebc1e8f62021-11-17 20:39:56 +0100574 # characters (or underscore, asterisk, or open parenthesis),
Gilles Peskine152de232021-11-16 20:56:47 +0100575 # and nothing else, high chance it's a declaration that
576 # continues on the next line
577 if re.search(r"^([\w\*\(]+\s+)+$", line):
578 previous_line += line
579 continue
580
581 # If previous line seemed to start an unfinished declaration
582 # (as above), concat and treat them as one.
583 if previous_line:
584 line = previous_line.strip() + " " + line.strip() + "\n"
585 previous_line = ""
586
587 # Skip parsing if line has a space in front = heuristic to
588 # skip function argument lines (highly subject to formatting
589 # changes)
590 if line[0] == " ":
591 continue
592
593 identifier = self.IDENTIFIER_REGEX.search(line)
594
595 if not identifier:
596 continue
597
598 # Find the group that matched, and append it
599 for group in identifier.groups():
600 if not group:
601 continue
602
603 identifiers.append(Match(
604 header_file,
605 line,
606 line_no,
607 identifier.span(),
608 group))
609
Yuto Takano8e9a2192021-08-09 14:48:53 +0100610 def parse_identifiers(self, include, exclude=None):
Yuto Takano39639672021-08-05 19:47:48 +0100611 """
Yuto Takano8246eb82021-08-16 10:37:24 +0100612 Parse all lines of a header where a function/enum/struct/union/typedef
Yuto Takanob1417b42021-08-17 10:30:20 +0100613 identifier is declared, based on some regex and heuristics. Highly
614 dependent on formatting style.
Darryl Greend5802922018-05-08 15:30:59 +0100615
Yuto Takano39639672021-08-05 19:47:48 +0100616 Args:
Yuto Takano8e9a2192021-08-09 14:48:53 +0100617 * include: A List of glob expressions to look for files through.
618 * exclude: A List of glob expressions for excluding files.
Yuto Takano81528c02021-08-06 16:22:06 +0100619
620 Returns a List of Match objects with identifiers.
Yuto Takano39639672021-08-05 19:47:48 +0100621 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100622
Yuto Takano50953432021-08-09 14:54:36 +0100623 files = self.get_files(include, exclude)
624 self.log.debug("Looking for identifiers in {} files".format(len(files)))
625
626 identifiers = []
627 for header_file in files:
Gilles Peskine152de232021-11-16 20:56:47 +0100628 self.parse_identifiers_in_file(header_file, identifiers)
Yuto Takano39639672021-08-05 19:47:48 +0100629
630 return identifiers
631
632 def parse_symbols(self):
633 """
634 Compile the Mbed TLS libraries, and parse the TLS, Crypto, and x509
635 object files using nm to retrieve the list of referenced symbols.
Yuto Takano81528c02021-08-06 16:22:06 +0100636 Exceptions thrown here are rethrown because they would be critical
637 errors that void several tests, and thus needs to halt the program. This
638 is explicitly done for clarity.
Yuto Takano39639672021-08-05 19:47:48 +0100639
Yuto Takano81528c02021-08-06 16:22:06 +0100640 Returns a List of unique symbols defined and used in the libraries.
641 """
642 self.log.info("Compiling...")
Yuto Takano39639672021-08-05 19:47:48 +0100643 symbols = []
644
Tom Cosgrove1797b052022-12-04 17:19:59 +0000645 # Back up the config and atomically compile with the full configuration.
Yuto Takanod70d4462021-08-09 12:45:51 +0100646 shutil.copy(
647 "include/mbedtls/mbedtls_config.h",
648 "include/mbedtls/mbedtls_config.h.bak"
649 )
Darryl Greend5802922018-05-08 15:30:59 +0100650 try:
Yuto Takano81528c02021-08-06 16:22:06 +0100651 # Use check=True in all subprocess calls so that failures are raised
652 # as exceptions and logged.
Yuto Takano39639672021-08-05 19:47:48 +0100653 subprocess.run(
Yuto Takano81528c02021-08-06 16:22:06 +0100654 ["python3", "scripts/config.py", "full"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100655 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100656 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100657 )
658 my_environment = os.environ.copy()
659 my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
Yuto Takano4b7d23d2021-08-17 10:48:22 +0100660 # Run make clean separately to lib to prevent unwanted behavior when
661 # make is invoked with parallelism.
Yuto Takano39639672021-08-05 19:47:48 +0100662 subprocess.run(
Yuto Takano4b7d23d2021-08-17 10:48:22 +0100663 ["make", "clean"],
664 universal_newlines=True,
665 check=True
666 )
667 subprocess.run(
668 ["make", "lib"],
Darryl Greend5802922018-05-08 15:30:59 +0100669 env=my_environment,
Yuto Takanobcc3d992021-08-06 23:14:58 +0100670 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100671 stdout=subprocess.PIPE,
Darryl Greend5802922018-05-08 15:30:59 +0100672 stderr=subprocess.STDOUT,
Yuto Takano39639672021-08-05 19:47:48 +0100673 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100674 )
Yuto Takano39639672021-08-05 19:47:48 +0100675
676 # Perform object file analysis using nm
Yuto Takanod70d4462021-08-09 12:45:51 +0100677 symbols = self.parse_symbols_from_nm([
678 "library/libmbedcrypto.a",
679 "library/libmbedtls.a",
680 "library/libmbedx509.a"
681 ])
Yuto Takano39639672021-08-05 19:47:48 +0100682
683 subprocess.run(
Darryl Greend5802922018-05-08 15:30:59 +0100684 ["make", "clean"],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100685 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100686 check=True
Darryl Greend5802922018-05-08 15:30:59 +0100687 )
688 except subprocess.CalledProcessError as error:
Yuto Takano25eeb7b2021-08-06 21:27:59 +0100689 self.log.debug(error.output)
Yuto Takano81528c02021-08-06 16:22:06 +0100690 raise error
Yuto Takano39639672021-08-05 19:47:48 +0100691 finally:
Yuto Takano6fececf2021-08-07 17:28:23 +0100692 # Put back the original config regardless of there being errors.
693 # Works also for keyboard interrupts.
Yuto Takanod70d4462021-08-09 12:45:51 +0100694 shutil.move(
695 "include/mbedtls/mbedtls_config.h.bak",
696 "include/mbedtls/mbedtls_config.h"
697 )
Yuto Takano39639672021-08-05 19:47:48 +0100698
699 return symbols
700
701 def parse_symbols_from_nm(self, object_files):
702 """
703 Run nm to retrieve the list of referenced symbols in each object file.
704 Does not return the position data since it is of no use.
705
Yuto Takano81528c02021-08-06 16:22:06 +0100706 Args:
Yuto Takano55c6c872021-08-09 15:35:19 +0100707 * object_files: a List of compiled object filepaths to search through.
Yuto Takano81528c02021-08-06 16:22:06 +0100708
709 Returns a List of unique symbols defined and used in any of the object
710 files.
Yuto Takano39639672021-08-05 19:47:48 +0100711 """
Yuto Takanod93fa372021-08-06 23:05:55 +0100712 nm_undefined_regex = re.compile(r"^\S+: +U |^$|^\S+:$")
713 nm_valid_regex = re.compile(r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)")
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100714 exclusions = ("FStar", "Hacl")
Yuto Takano39639672021-08-05 19:47:48 +0100715
716 symbols = []
717
Yuto Takano81528c02021-08-06 16:22:06 +0100718 # Gather all outputs of nm
Yuto Takano39639672021-08-05 19:47:48 +0100719 nm_output = ""
720 for lib in object_files:
721 nm_output += subprocess.run(
722 ["nm", "-og", lib],
Yuto Takanobcc3d992021-08-06 23:14:58 +0100723 universal_newlines=True,
Yuto Takano39639672021-08-05 19:47:48 +0100724 stdout=subprocess.PIPE,
725 stderr=subprocess.STDOUT,
726 check=True
727 ).stdout
Yuto Takano81528c02021-08-06 16:22:06 +0100728
Yuto Takano39639672021-08-05 19:47:48 +0100729 for line in nm_output.splitlines():
Yuto Takano90bc0262021-08-16 11:34:10 +0100730 if not nm_undefined_regex.search(line):
731 symbol = nm_valid_regex.search(line)
Yuto Takano12a7ecd2021-08-07 00:40:29 +0100732 if (symbol and not symbol.group("symbol").startswith(exclusions)):
Yuto Takanoe77f6992021-08-05 20:22:59 +0100733 symbols.append(symbol.group("symbol"))
Yuto Takano39639672021-08-05 19:47:48 +0100734 else:
735 self.log.error(line)
Yuto Takano81528c02021-08-06 16:22:06 +0100736
Yuto Takano39639672021-08-05 19:47:48 +0100737 return symbols
738
Yuto Takano55c6c872021-08-09 15:35:19 +0100739class NameChecker():
740 """
741 Representation of the core name checking operation performed by this script.
742 """
743 def __init__(self, parse_result, log):
744 self.parse_result = parse_result
745 self.log = log
746
Yuto Takano55614b52021-08-07 01:00:18 +0100747 def perform_checks(self, quiet=False):
Yuto Takano39639672021-08-05 19:47:48 +0100748 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100749 A comprehensive checker that performs each check in order, and outputs
750 a final verdict.
Yuto Takano81528c02021-08-06 16:22:06 +0100751
752 Args:
Yuto Takano55614b52021-08-07 01:00:18 +0100753 * quiet: whether to hide detailed problem explanation.
Yuto Takano39639672021-08-05 19:47:48 +0100754 """
Yuto Takano81528c02021-08-06 16:22:06 +0100755 self.log.info("=============")
Yuto Takano5473be22021-08-17 10:14:01 +0100756 Problem.quiet = quiet
Yuto Takano39639672021-08-05 19:47:48 +0100757 problems = 0
Yuto Takano5473be22021-08-17 10:14:01 +0100758 problems += self.check_symbols_declared_in_header()
Yuto Takano39639672021-08-05 19:47:48 +0100759
Yuto Takanod70d4462021-08-09 12:45:51 +0100760 pattern_checks = [
Janos Follath99387192022-08-10 11:11:34 +0100761 ("public_macros", PUBLIC_MACRO_PATTERN),
762 ("internal_macros", INTERNAL_MACRO_PATTERN),
Yuto Takanod70d4462021-08-09 12:45:51 +0100763 ("enum_consts", CONSTANTS_PATTERN),
764 ("identifiers", IDENTIFIER_PATTERN)
765 ]
Yuto Takano39639672021-08-05 19:47:48 +0100766 for group, check_pattern in pattern_checks:
Yuto Takano5473be22021-08-17 10:14:01 +0100767 problems += self.check_match_pattern(group, check_pattern)
Yuto Takano39639672021-08-05 19:47:48 +0100768
Yuto Takano5473be22021-08-17 10:14:01 +0100769 problems += self.check_for_typos()
Yuto Takano39639672021-08-05 19:47:48 +0100770
771 self.log.info("=============")
772 if problems > 0:
773 self.log.info("FAIL: {0} problem(s) to fix".format(str(problems)))
Yuto Takano55614b52021-08-07 01:00:18 +0100774 if quiet:
775 self.log.info("Remove --quiet to see explanations.")
Yuto Takanofc54dfb2021-08-07 17:18:28 +0100776 else:
777 self.log.info("Use --quiet for minimal output.")
Yuto Takano55c6c872021-08-09 15:35:19 +0100778 return 1
Yuto Takano39639672021-08-05 19:47:48 +0100779 else:
780 self.log.info("PASS")
Yuto Takano55c6c872021-08-09 15:35:19 +0100781 return 0
Darryl Greend5802922018-05-08 15:30:59 +0100782
Yuto Takano5473be22021-08-17 10:14:01 +0100783 def check_symbols_declared_in_header(self):
Yuto Takano39639672021-08-05 19:47:48 +0100784 """
785 Perform a check that all detected symbols in the library object files
786 are properly declared in headers.
Yuto Takano977e07f2021-08-09 11:56:15 +0100787 Assumes parse_names_in_source() was called before this.
Darryl Greend5802922018-05-08 15:30:59 +0100788
Yuto Takano81528c02021-08-06 16:22:06 +0100789 Returns the number of problems that need fixing.
Yuto Takano39639672021-08-05 19:47:48 +0100790 """
791 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100792
Yuto Takano39639672021-08-05 19:47:48 +0100793 for symbol in self.parse_result["symbols"]:
794 found_symbol_declared = False
795 for identifier_match in self.parse_result["identifiers"]:
796 if symbol == identifier_match.name:
797 found_symbol_declared = True
798 break
Yuto Takano81528c02021-08-06 16:22:06 +0100799
Yuto Takano39639672021-08-05 19:47:48 +0100800 if not found_symbol_declared:
Yuto Takanod70d4462021-08-09 12:45:51 +0100801 problems.append(SymbolNotInHeader(symbol))
Yuto Takano39639672021-08-05 19:47:48 +0100802
Yuto Takano5473be22021-08-17 10:14:01 +0100803 self.output_check_result("All symbols in header", problems)
Yuto Takano39639672021-08-05 19:47:48 +0100804 return len(problems)
805
Yuto Takano5473be22021-08-17 10:14:01 +0100806 def check_match_pattern(self, group_to_check, check_pattern):
Yuto Takano81528c02021-08-06 16:22:06 +0100807 """
808 Perform a check that all items of a group conform to a regex pattern.
Yuto Takano977e07f2021-08-09 11:56:15 +0100809 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100810
811 Args:
Yuto Takano81528c02021-08-06 16:22:06 +0100812 * group_to_check: string key to index into self.parse_result.
813 * check_pattern: the regex to check against.
814
815 Returns the number of problems that need fixing.
816 """
Yuto Takano39639672021-08-05 19:47:48 +0100817 problems = []
Yuto Takanod93fa372021-08-06 23:05:55 +0100818
Yuto Takano39639672021-08-05 19:47:48 +0100819 for item_match in self.parse_result[group_to_check]:
Yuto Takano90bc0262021-08-16 11:34:10 +0100820 if not re.search(check_pattern, item_match.name):
Yuto Takano39639672021-08-05 19:47:48 +0100821 problems.append(PatternMismatch(check_pattern, item_match))
Yuto Takano90bc0262021-08-16 11:34:10 +0100822 # Double underscore should not be used for names
823 if re.search(r".*__.*", item_match.name):
Yuto Takano704b0f72021-08-17 10:41:23 +0100824 problems.append(
825 PatternMismatch("no double underscore allowed", item_match))
Yuto Takano81528c02021-08-06 16:22:06 +0100826
827 self.output_check_result(
828 "Naming patterns of {}".format(group_to_check),
Yuto Takano55614b52021-08-07 01:00:18 +0100829 problems)
Yuto Takano39639672021-08-05 19:47:48 +0100830 return len(problems)
Darryl Greend5802922018-05-08 15:30:59 +0100831
Yuto Takano5473be22021-08-17 10:14:01 +0100832 def check_for_typos(self):
Yuto Takano81528c02021-08-06 16:22:06 +0100833 """
Shaun Case8b0ecbc2021-12-20 21:14:10 -0800834 Perform a check that all words in the source code beginning with MBED are
Yuto Takano81528c02021-08-06 16:22:06 +0100835 either defined as macros, or as enum constants.
Yuto Takano977e07f2021-08-09 11:56:15 +0100836 Assumes parse_names_in_source() was called before this.
Yuto Takano81528c02021-08-06 16:22:06 +0100837
Yuto Takano81528c02021-08-06 16:22:06 +0100838 Returns the number of problems that need fixing.
839 """
Yuto Takano39639672021-08-05 19:47:48 +0100840 problems = []
Yuto Takano39639672021-08-05 19:47:48 +0100841
Yuto Takanod70d4462021-08-09 12:45:51 +0100842 # Set comprehension, equivalent to a list comprehension wrapped by set()
Yuto Takanod93fa372021-08-06 23:05:55 +0100843 all_caps_names = {
844 match.name
845 for match
Janos Follath99387192022-08-10 11:11:34 +0100846 in self.parse_result["public_macros"] +
Janos Follath8d59c862022-08-10 15:35:35 +0100847 self.parse_result["internal_macros"] +
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800848 self.parse_result["private_macros"] +
Janos Follath8d59c862022-08-10 15:35:35 +0100849 self.parse_result["enum_consts"]
Janos Follath99387192022-08-10 11:11:34 +0100850 }
Ronald Cron7975fae2021-09-13 14:50:42 +0200851 typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$|"
Pengyu Lvf3f1f812022-11-08 16:56:51 +0800852 r"MBEDTLS_TEST_LIBTESTDRIVER*|"
Pengyu Lv3bb0e432022-11-24 17:29:05 +0800853 r"PSA_CRYPTO_DRIVER_TEST")
Yuto Takano39639672021-08-05 19:47:48 +0100854
Pengyu Lvcdac0d52022-11-08 15:55:00 +0800855 for name_match in self.parse_result["mbed_psa_words"]:
Yuto Takano81528c02021-08-06 16:22:06 +0100856 found = name_match.name in all_caps_names
857
858 # Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
859 # PSA driver, they will not exist as macros. However, they
860 # should still be checked for typos using the equivalent
861 # BUILTINs that exist.
862 if "MBEDTLS_PSA_ACCEL_" in name_match.name:
863 found = name_match.name.replace(
864 "MBEDTLS_PSA_ACCEL_",
865 "MBEDTLS_PSA_BUILTIN_") in all_caps_names
866
Yuto Takanod93fa372021-08-06 23:05:55 +0100867 if not found and not typo_exclusion.search(name_match.name):
Yuto Takanod70d4462021-08-09 12:45:51 +0100868 problems.append(Typo(name_match))
Yuto Takano39639672021-08-05 19:47:48 +0100869
Yuto Takano5473be22021-08-17 10:14:01 +0100870 self.output_check_result("Likely typos", problems)
Yuto Takano81528c02021-08-06 16:22:06 +0100871 return len(problems)
872
Yuto Takano5473be22021-08-17 10:14:01 +0100873 def output_check_result(self, name, problems):
Yuto Takano81528c02021-08-06 16:22:06 +0100874 """
875 Write out the PASS/FAIL status of a performed check depending on whether
876 there were problems.
Yuto Takanod70d4462021-08-09 12:45:51 +0100877
878 Args:
Yuto Takanod70d4462021-08-09 12:45:51 +0100879 * name: the name of the test
880 * problems: a List of encountered Problems
Yuto Takano81528c02021-08-06 16:22:06 +0100881 """
Yuto Takano39639672021-08-05 19:47:48 +0100882 if problems:
Yuto Takano55614b52021-08-07 01:00:18 +0100883 self.log.info("{}: FAIL\n".format(name))
884 for problem in problems:
885 self.log.warning(str(problem))
Darryl Greend5802922018-05-08 15:30:59 +0100886 else:
Yuto Takano81528c02021-08-06 16:22:06 +0100887 self.log.info("{}: PASS".format(name))
Darryl Greend5802922018-05-08 15:30:59 +0100888
Yuto Takano39639672021-08-05 19:47:48 +0100889def main():
890 """
Yuto Takano55c6c872021-08-09 15:35:19 +0100891 Perform argument parsing, and create an instance of CodeParser and
892 NameChecker to begin the core operation.
Yuto Takano39639672021-08-05 19:47:48 +0100893 """
Yuto Takanof005c332021-08-09 13:56:36 +0100894 parser = argparse.ArgumentParser(
Yuto Takano39639672021-08-05 19:47:48 +0100895 formatter_class=argparse.RawDescriptionHelpFormatter,
896 description=(
897 "This script confirms that the naming of all symbols and identifiers "
898 "in Mbed TLS are consistent with the house style and are also "
899 "self-consistent.\n\n"
Yuto Takanof005c332021-08-09 13:56:36 +0100900 "Expected to be run from the MbedTLS root directory.")
901 )
902 parser.add_argument(
903 "-v", "--verbose",
904 action="store_true",
905 help="show parse results"
906 )
907 parser.add_argument(
908 "-q", "--quiet",
909 action="store_true",
Tom Cosgrove1797b052022-12-04 17:19:59 +0000910 help="hide unnecessary text, explanations, and highlights"
Yuto Takanof005c332021-08-09 13:56:36 +0100911 )
Darryl Greend5802922018-05-08 15:30:59 +0100912
Yuto Takanof005c332021-08-09 13:56:36 +0100913 args = parser.parse_args()
Darryl Greend5802922018-05-08 15:30:59 +0100914
Yuto Takano55c6c872021-08-09 15:35:19 +0100915 # Configure the global logger, which is then passed to the classes below
916 log = logging.getLogger()
917 log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
918 log.addHandler(logging.StreamHandler())
919
Darryl Greend5802922018-05-08 15:30:59 +0100920 try:
Yuto Takano55c6c872021-08-09 15:35:19 +0100921 code_parser = CodeParser(log)
922 parse_result = code_parser.comprehensive_parse()
Yuto Takanod93fa372021-08-06 23:05:55 +0100923 except Exception: # pylint: disable=broad-except
Darryl Greend5802922018-05-08 15:30:59 +0100924 traceback.print_exc()
925 sys.exit(2)
926
Yuto Takano55c6c872021-08-09 15:35:19 +0100927 name_checker = NameChecker(parse_result, log)
928 return_code = name_checker.perform_checks(quiet=args.quiet)
929
930 sys.exit(return_code)
931
Darryl Greend5802922018-05-08 15:30:59 +0100932if __name__ == "__main__":
Yuto Takano39639672021-08-05 19:47:48 +0100933 main()