blob: 3262342a2623eaf0a3ec7ef010dc1374713faef0 [file] [log] [blame]
Darryl Greenda02eb32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine081daf02019-07-04 19:31:02 +02002
Gilles Peskine081daf02019-07-04 19:31:02 +02003# Copyright (c) 2018, Arm Limited, All Rights Reserved
Bence Szépkúti09b4f192020-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 Peskine081daf02019-07-04 19:31:02 +020019
Darryl Greenda02eb32018-02-28 10:02:55 +000020"""
Darryl Greenda02eb32018-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 Peskine570f7a22019-07-04 19:31:33 +020023trailing whitespace, and presence of UTF-8 BOM.
Darryl Greenda02eb32018-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 Peskineb4805ec2020-05-10 16:57:16 +020031import re
Gilles Peskine4bda3252020-05-10 17:18:06 +020032import subprocess
Darryl Greenda02eb32018-02-28 10:02:55 +000033import sys
34
35
Gilles Peskineb5847d22020-03-24 18:25:17 +010036class FileIssueTracker:
Gilles Peskine7194ecb2019-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 Peskinefb8c3732019-02-25 21:10:04 +010040 this class and implement `check_file_for_issue` and define ``heading``.
41
Gilles Peskine45137612020-05-10 16:52:44 +020042 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskinefb8c3732019-02-25 21:10:04 +010043 will not be checked.
44
Gilles Peskineb4805ec2020-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 Peskinefb8c3732019-02-25 21:10:04 +010050 ``heading``: human-readable description of the issue
Gilles Peskine7194ecb2019-02-25 20:59:05 +010051 """
Darryl Greenda02eb32018-02-28 10:02:55 +000052
Gilles Peskine45137612020-05-10 16:52:44 +020053 suffix_exemptions = frozenset()
Gilles Peskineb4805ec2020-05-10 16:57:16 +020054 path_exemptions = None
Gilles Peskinefb8c3732019-02-25 21:10:04 +010055 # heading must be defined in derived classes.
56 # pylint: disable=no-member
57
Darryl Greenda02eb32018-02-28 10:02:55 +000058 def __init__(self):
Darryl Greenda02eb32018-02-28 10:02:55 +000059 self.files_with_issues = {}
60
Gilles Peskineb4805ec2020-05-10 16:57:16 +020061 @staticmethod
62 def normalize_path(filepath):
Gilles Peskine14b559a2020-05-28 18:19:20 +020063 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskineb4805ec2020-05-10 16:57:16 +020064 filepath = os.path.normpath(filepath)
Gilles Peskine14b559a2020-05-28 18:19:20 +020065 # On Windows, we may have backslashes to separate directories.
66 # We need slashes to match exemption lists.
Gilles Peskineb4805ec2020-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 Greenda02eb32018-02-28 10:02:55 +000072 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010073 """Whether the given file name should be checked.
74
Gilles Peskine45137612020-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 Peskine558e26d2020-03-24 16:49:21 +010077 """
Gilles Peskine45137612020-05-10 16:52:44 +020078 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +000079 if filepath.endswith(files_exemption):
80 return False
Gilles Peskineb4805ec2020-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 Greenda02eb32018-02-28 10:02:55 +000084 return True
85
Darryl Greenda02eb32018-02-28 10:02:55 +000086 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-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 Peskine7194ecb2019-02-25 20:59:05 +010091 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000092
Gilles Peskine232fae32018-11-23 21:11:30 +010093 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +010094 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-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 Greenda02eb32018-02-28 10:02:55 +000099 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100100 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-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 Peskine986a06d2020-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 Peskine7194ecb2019-02-25 20:59:05 +0100123class LineIssueTracker(FileIssueTracker):
124 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +0000125
Gilles Peskine7194ecb2019-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 Peskine986a06d2020-05-10 16:57:59 +0200130 # Exclude binary files.
131 path_exemptions = BINARY_FILE_PATH_RE
132
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100133 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine227dfd42020-03-24 22:26:01 +0100153
154def is_windows_file(filepath):
155 _root, ext = os.path.splitext(filepath)
Gilles Peskinee7e149f2020-05-10 17:36:51 +0200156 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100157
158
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100159class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100160 """Track files with bad permissions.
161
162 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000163
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100164 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000165
166 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-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 Greenda02eb32018-02-28 10:02:55 +0000170 self.files_with_issues[filepath] = None
171
172
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100173class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000176
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100177 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000178
Gilles Peskine986a06d2020-05-10 16:57:59 +0200179 path_exemptions = BINARY_FILE_PATH_RE
180
Darryl Greenda02eb32018-02-28 10:02:55 +0000181 def check_file_for_issue(self, filepath):
182 with open(filepath, "rb") as f:
Gilles Peskinebe76c192020-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 Greenda02eb32018-02-28 10:02:55 +0000191 self.files_with_issues[filepath] = None
192
193
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100194class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000197
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100198 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000199
Gilles Peskine45137612020-05-10 16:52:44 +0200200 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine986a06d2020-05-10 16:57:59 +0200201 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine227dfd42020-03-24 22:26:01 +0100202
Darryl Greenda02eb32018-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 Peskine227dfd42020-03-24 22:26:01 +0100209class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100210 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000211
Gilles Peskine227dfd42020-03-24 22:26:01 +0100212 heading = "Non-Unix line endings:"
213
214 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200215 if not super().should_check_file(filepath):
216 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100217 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000218
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100219 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000220 return b"\r" in line
221
222
Gilles Peskine783da632020-03-24 22:29:11 +0100223class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200224 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100225
226 heading = "Non-Windows line endings:"
227
228 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200229 if not super().should_check_file(filepath):
230 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100231 return is_windows_file(filepath)
232
233 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200234 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100235
236
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100237class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100238 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000239
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100240 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200241 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000242
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100243 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000244 return line.rstrip(b"\r\n") != line.rstrip()
245
246
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100247class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100248 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000249
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100250 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200251 suffix_exemptions = frozenset([
Gilles Peskine8fa5be52020-05-10 17:37:02 +0200252 ".pem", # some openssl dumps have tabs
Gilles Peskine227dfd42020-03-24 22:26:01 +0100253 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100254 "/Makefile",
255 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100256 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000257
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100258 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000259 return b"\t" in line
260
261
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100262class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100263 """Track lines with merge artifacts.
264 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100265
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100266 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100267
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100268 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100269 # Detect leftover git conflict markers.
270 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
271 return True
272 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
273 return True
274 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100275 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100276 return True
277 return False
278
Darryl Greenda02eb32018-02-28 10:02:55 +0000279
Gilles Peskineb5847d22020-03-24 18:25:17 +0100280class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100281 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000282
283 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100284 """Instantiate the sanity checker.
285 Check files under the current directory.
286 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000287 self.check_repo_path()
288 self.logger = None
289 self.setup_logger(log_file)
Darryl Greenda02eb32018-02-28 10:02:55 +0000290 self.issues_to_check = [
291 PermissionIssueTracker(),
292 EndOfFileNewlineIssueTracker(),
293 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100294 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100295 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000296 TrailingWhitespaceIssueTracker(),
297 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100298 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000299 ]
300
Gilles Peskine4fb66782019-02-25 20:35:31 +0100301 @staticmethod
302 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000303 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
304 raise Exception("Must be run from Mbed TLS root")
305
306 def setup_logger(self, log_file, level=logging.INFO):
307 self.logger = logging.getLogger()
308 self.logger.setLevel(level)
309 if log_file:
310 handler = logging.FileHandler(log_file)
311 self.logger.addHandler(handler)
312 else:
313 console = logging.StreamHandler()
314 self.logger.addHandler(console)
315
Gilles Peskine4bda3252020-05-10 17:18:06 +0200316 @staticmethod
317 def collect_files():
318 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
319 bytes_filepaths = bytes_output.split(b'\0')[:-1]
320 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
321 # Prepend './' to files in the top-level directory so that
322 # something like `'/Makefile' in fp` matches in the top-level
323 # directory as well as in subdirectories.
324 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
325 for fp in ascii_filepaths]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200326
Darryl Greenda02eb32018-02-28 10:02:55 +0000327 def check_files(self):
Gilles Peskine4bda3252020-05-10 17:18:06 +0200328 for issue_to_check in self.issues_to_check:
329 for filepath in self.collect_files():
330 if issue_to_check.should_check_file(filepath):
331 issue_to_check.check_file_for_issue(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000332
333 def output_issues(self):
334 integrity_return_code = 0
335 for issue_to_check in self.issues_to_check:
336 if issue_to_check.files_with_issues:
337 integrity_return_code = 1
338 issue_to_check.output_file_issues(self.logger)
339 return integrity_return_code
340
341
342def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200343 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000344 parser.add_argument(
345 "-l", "--log_file", type=str, help="path to optional output log",
346 )
347 check_args = parser.parse_args()
348 integrity_check = IntegrityChecker(check_args.log_file)
349 integrity_check.check_files()
350 return_code = integrity_check.output_issues()
351 sys.exit(return_code)
352
353
354if __name__ == "__main__":
355 run_main()