blob: 1cef2d5f191e27163bdff99ac86de7c66482cfce [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02002
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02003# Copyright (c) 2018, Arm Limited, All Rights Reserved
Bence Szépkútic7da1fe2020-05-26 01:54:15 +02004# 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#
18# This file is part of Mbed TLS (https://tls.mbed.org)
Gilles Peskine7dfcfce2019-07-04 19:31:02 +020019
Darryl Green10d9ce32018-02-28 10:02:55 +000020"""
Darryl Green10d9ce32018-02-28 10:02:55 +000021This script checks the current state of the source code for minor issues,
22including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine55b49ee2019-07-04 19:31:33 +020023trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-02-28 10:02:55 +000024Note: requires python 3, must be run from Mbed TLS root.
25"""
26
27import os
28import argparse
29import logging
30import codecs
Gilles Peskine0598db82020-05-10 16:57:16 +020031import re
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +020032import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000033import sys
34
35
Gilles Peskine184c0962020-03-24 18:25:17 +010036class FileIssueTracker:
Gilles Peskine6ee576e2019-02-25 20:59:05 +010037 """Base class for file-wide issue tracking.
38
39 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine1e9698a2019-02-25 21:10:04 +010040 this class and implement `check_file_for_issue` and define ``heading``.
41
Gilles Peskine05a51a82020-05-10 16:52:44 +020042 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010043 will not be checked.
44
Gilles Peskine0598db82020-05-10 16:57:16 +020045 ``path_exemptions``: files whose path (relative to the root of the source
46 tree) matches this regular expression will not be checked. This can be
47 ``None`` to match no path. Paths are normalized and converted to ``/``
48 separators before matching.
49
Gilles Peskine1e9698a2019-02-25 21:10:04 +010050 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010051 """
Darryl Green10d9ce32018-02-28 10:02:55 +000052
Gilles Peskine05a51a82020-05-10 16:52:44 +020053 suffix_exemptions = frozenset()
Gilles Peskine0598db82020-05-10 16:57:16 +020054 path_exemptions = None
Gilles Peskine1e9698a2019-02-25 21:10:04 +010055 # heading must be defined in derived classes.
56 # pylint: disable=no-member
57
Darryl Green10d9ce32018-02-28 10:02:55 +000058 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000059 self.files_with_issues = {}
60
Gilles Peskine0598db82020-05-10 16:57:16 +020061 @staticmethod
62 def normalize_path(filepath):
Gilles Peskineeca95db2020-05-28 18:19:20 +020063 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskine0598db82020-05-10 16:57:16 +020064 filepath = os.path.normpath(filepath)
Gilles Peskineeca95db2020-05-28 18:19:20 +020065 # On Windows, we may have backslashes to separate directories.
66 # We need slashes to match exemption lists.
Gilles Peskine0598db82020-05-10 16:57:16 +020067 seps = os.path.sep
68 if os.path.altsep is not None:
69 seps += os.path.altsep
70 return '/'.join(filepath.split(seps))
71
Darryl Green10d9ce32018-02-28 10:02:55 +000072 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010073 """Whether the given file name should be checked.
74
Gilles Peskine05a51a82020-05-10 16:52:44 +020075 Files whose name ends with a string listed in ``self.suffix_exemptions``
76 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010077 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020078 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000079 if filepath.endswith(files_exemption):
80 return False
Gilles Peskine0598db82020-05-10 16:57:16 +020081 if self.path_exemptions and \
82 re.match(self.path_exemptions, self.normalize_path(filepath)):
83 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000084 return True
85
Darryl Green10d9ce32018-02-28 10:02:55 +000086 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010087 """Check the specified file for the issue that this class is for.
88
89 Subclasses must implement this method.
90 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010091 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000092
Gilles Peskine04398052018-11-23 21:11:30 +010093 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010094 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010095 if filepath not in self.files_with_issues.keys():
96 self.files_with_issues[filepath] = []
97 self.files_with_issues[filepath].append(line_number)
98
Darryl Green10d9ce32018-02-28 10:02:55 +000099 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100100 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000101 if self.files_with_issues.values():
102 logger.info(self.heading)
103 for filename, lines in sorted(self.files_with_issues.items()):
104 if lines:
105 logger.info("{}: {}".format(
106 filename, ", ".join(str(x) for x in lines)
107 ))
108 else:
109 logger.info(filename)
110 logger.info("")
111
Gilles Peskined4a853d2020-05-10 16:57:59 +0200112BINARY_FILE_PATH_RE_LIST = [
113 r'docs/.*\.pdf\Z',
114 r'programs/fuzz/corpuses/[^.]+\Z',
115 r'tests/data_files/[^.]+\Z',
116 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
117 r'tests/data_files/.*\.req\.[^/]+\Z',
118 r'tests/data_files/.*malformed[^/]+\Z',
119 r'tests/data_files/format_pkcs12\.fmt\Z',
120]
121BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
122
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100123class LineIssueTracker(FileIssueTracker):
124 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000125
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100126 To implement a checker that processes files line by line, inherit from
127 this class and implement `line_with_issue`.
128 """
129
Gilles Peskined4a853d2020-05-10 16:57:59 +0200130 # Exclude binary files.
131 path_exemptions = BINARY_FILE_PATH_RE
132
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100133 def issue_with_line(self, line, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100134 """Check the specified line for the issue that this class is for.
135
136 Subclasses must implement this method.
137 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100138 raise NotImplementedError
139
140 def check_file_line(self, filepath, line, line_number):
141 if self.issue_with_line(line, filepath):
142 self.record_issue(filepath, line_number)
143
144 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100145 """Check the lines of the specified file.
146
147 Subclasses must implement the ``issue_with_line`` method.
148 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100149 with open(filepath, "rb") as f:
150 for i, line in enumerate(iter(f.readline, b"")):
151 self.check_file_line(filepath, line, i + 1)
152
Gilles Peskine2c618732020-03-24 22:26:01 +0100153
154def is_windows_file(filepath):
155 _root, ext = os.path.splitext(filepath)
Gilles Peskined2df86f2020-05-10 17:36:51 +0200156 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100157
158
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100159class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100160 """Track files with bad permissions.
161
162 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000163
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100164 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000165
166 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100167 is_executable = os.access(filepath, os.X_OK)
168 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
169 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000170 self.files_with_issues[filepath] = None
171
172
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100173class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100174 """Track files that end with an incomplete line
175 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000176
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100177 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000178
Gilles Peskined4a853d2020-05-10 16:57:59 +0200179 path_exemptions = BINARY_FILE_PATH_RE
180
Darryl Green10d9ce32018-02-28 10:02:55 +0000181 def check_file_for_issue(self, filepath):
182 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200183 try:
184 f.seek(-1, 2)
185 except OSError:
186 # This script only works on regular files. If we can't seek
187 # 1 before the end, it means that this position is before
188 # the beginning of the file, i.e. that the file is empty.
189 return
190 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000191 self.files_with_issues[filepath] = None
192
193
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100194class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100195 """Track files that start with a UTF-8 BOM.
196 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000197
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100198 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000199
Gilles Peskine05a51a82020-05-10 16:52:44 +0200200 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200201 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100202
Darryl Green10d9ce32018-02-28 10:02:55 +0000203 def check_file_for_issue(self, filepath):
204 with open(filepath, "rb") as f:
205 if f.read().startswith(codecs.BOM_UTF8):
206 self.files_with_issues[filepath] = None
207
208
Gilles Peskine2c618732020-03-24 22:26:01 +0100209class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100210 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000211
Gilles Peskine2c618732020-03-24 22:26:01 +0100212 heading = "Non-Unix line endings:"
213
214 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200215 if not super().should_check_file(filepath):
216 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100217 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000218
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100219 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000220 return b"\r" in line
221
222
Gilles Peskine545e13f2020-03-24 22:29:11 +0100223class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200224 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100225
226 heading = "Non-Windows line endings:"
227
228 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200229 if not super().should_check_file(filepath):
230 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100231 return is_windows_file(filepath)
232
233 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200234 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100235
236
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100237class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100238 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000239
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100240 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200241 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000242
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100243 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000244 return line.rstrip(b"\r\n") != line.rstrip()
245
246
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100247class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100248 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000249
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100250 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200251 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200252 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100253 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100254 "/Makefile",
255 "/Makefile.inc",
256 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100257 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000258
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100259 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000260 return b"\t" in line
261
262
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100263class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100264 """Track lines with merge artifacts.
265 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100266
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100267 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100268
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100269 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100270 # Detect leftover git conflict markers.
271 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
272 return True
273 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
274 return True
275 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100276 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100277 return True
278 return False
279
Darryl Green10d9ce32018-02-28 10:02:55 +0000280
Gilles Peskine184c0962020-03-24 18:25:17 +0100281class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100282 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000283
284 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100285 """Instantiate the sanity checker.
286 Check files under the current directory.
287 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000288 self.check_repo_path()
289 self.logger = None
290 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000291 self.issues_to_check = [
292 PermissionIssueTracker(),
293 EndOfFileNewlineIssueTracker(),
294 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100295 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100296 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000297 TrailingWhitespaceIssueTracker(),
298 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100299 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000300 ]
301
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100302 @staticmethod
303 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000304 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
305 raise Exception("Must be run from Mbed TLS root")
306
307 def setup_logger(self, log_file, level=logging.INFO):
308 self.logger = logging.getLogger()
309 self.logger.setLevel(level)
310 if log_file:
311 handler = logging.FileHandler(log_file)
312 self.logger.addHandler(handler)
313 else:
314 console = logging.StreamHandler()
315 self.logger.addHandler(console)
316
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200317 @staticmethod
318 def collect_files():
319 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
320 bytes_filepaths = bytes_output.split(b'\0')[:-1]
321 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
322 # Prepend './' to files in the top-level directory so that
323 # something like `'/Makefile' in fp` matches in the top-level
324 # directory as well as in subdirectories.
325 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
326 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200327
Darryl Green10d9ce32018-02-28 10:02:55 +0000328 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200329 for issue_to_check in self.issues_to_check:
330 for filepath in self.collect_files():
331 if issue_to_check.should_check_file(filepath):
332 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000333
334 def output_issues(self):
335 integrity_return_code = 0
336 for issue_to_check in self.issues_to_check:
337 if issue_to_check.files_with_issues:
338 integrity_return_code = 1
339 issue_to_check.output_file_issues(self.logger)
340 return integrity_return_code
341
342
343def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200344 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000345 parser.add_argument(
346 "-l", "--log_file", type=str, help="path to optional output log",
347 )
348 check_args = parser.parse_args()
349 integrity_check = IntegrityChecker(check_args.log_file)
350 integrity_check.check_files()
351 return_code = integrity_check.output_issues()
352 sys.exit(return_code)
353
354
355if __name__ == "__main__":
356 run_main()