blob: e7fa60b750c3a32e9d85eeeaf5c4f4c245252ce5 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine79cfef02019-07-04 19:31:02 +02002
3# This file is part of Mbed TLS (https://tls.mbed.org)
4# Copyright (c) 2018, Arm Limited, All Rights Reserved
5
Darryl Green10d9ce32018-02-28 10:02:55 +00006"""
Darryl Green10d9ce32018-02-28 10:02:55 +00007This script checks the current state of the source code for minor issues,
8including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine47d7c2d2019-07-04 19:31:33 +02009trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-02-28 10:02:55 +000010Note: requires python 3, must be run from Mbed TLS root.
11"""
12
13import os
14import argparse
15import logging
16import codecs
Gilles Peskinee6f1f242020-05-10 16:57:16 +020017import re
Darryl Green10d9ce32018-02-28 10:02:55 +000018import sys
19
20
Gilles Peskine5d1dfd42020-03-24 18:25:17 +010021class FileIssueTracker:
Gilles Peskined5240ec2019-02-25 20:59:05 +010022 """Base class for file-wide issue tracking.
23
24 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine21e85f72019-02-25 21:10:04 +010025 this class and implement `check_file_for_issue` and define ``heading``.
26
Gilles Peskinee856ba12020-05-10 16:52:44 +020027 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine21e85f72019-02-25 21:10:04 +010028 will not be checked.
29
Gilles Peskinee6f1f242020-05-10 16:57:16 +020030 ``path_exemptions``: files whose path (relative to the root of the source
31 tree) matches this regular expression will not be checked. This can be
32 ``None`` to match no path. Paths are normalized and converted to ``/``
33 separators before matching.
34
Gilles Peskine21e85f72019-02-25 21:10:04 +010035 ``heading``: human-readable description of the issue
Gilles Peskined5240ec2019-02-25 20:59:05 +010036 """
Darryl Green10d9ce32018-02-28 10:02:55 +000037
Gilles Peskinee856ba12020-05-10 16:52:44 +020038 suffix_exemptions = frozenset()
Gilles Peskinee6f1f242020-05-10 16:57:16 +020039 path_exemptions = None
Gilles Peskine21e85f72019-02-25 21:10:04 +010040 # heading must be defined in derived classes.
41 # pylint: disable=no-member
42
Darryl Green10d9ce32018-02-28 10:02:55 +000043 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000044 self.files_with_issues = {}
45
Gilles Peskinee6f1f242020-05-10 16:57:16 +020046 @staticmethod
47 def normalize_path(filepath):
48 """Normalize ``filepath`` """
49 filepath = os.path.normpath(filepath)
50 seps = os.path.sep
51 if os.path.altsep is not None:
52 seps += os.path.altsep
53 return '/'.join(filepath.split(seps))
54
Darryl Green10d9ce32018-02-28 10:02:55 +000055 def should_check_file(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010056 """Whether the given file name should be checked.
57
Gilles Peskinee856ba12020-05-10 16:52:44 +020058 Files whose name ends with a string listed in ``self.suffix_exemptions``
59 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010060 """
Gilles Peskinee856ba12020-05-10 16:52:44 +020061 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000062 if filepath.endswith(files_exemption):
63 return False
Gilles Peskinee6f1f242020-05-10 16:57:16 +020064 if self.path_exemptions and \
65 re.match(self.path_exemptions, self.normalize_path(filepath)):
66 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000067 return True
68
Darryl Green10d9ce32018-02-28 10:02:55 +000069 def check_file_for_issue(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010070 """Check the specified file for the issue that this class is for.
71
72 Subclasses must implement this method.
73 """
Gilles Peskined5240ec2019-02-25 20:59:05 +010074 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000075
Gilles Peskine04398052018-11-23 21:11:30 +010076 def record_issue(self, filepath, line_number):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010077 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010078 if filepath not in self.files_with_issues.keys():
79 self.files_with_issues[filepath] = []
80 self.files_with_issues[filepath].append(line_number)
81
Darryl Green10d9ce32018-02-28 10:02:55 +000082 def output_file_issues(self, logger):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +010083 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000084 if self.files_with_issues.values():
85 logger.info(self.heading)
86 for filename, lines in sorted(self.files_with_issues.items()):
87 if lines:
88 logger.info("{}: {}".format(
89 filename, ", ".join(str(x) for x in lines)
90 ))
91 else:
92 logger.info(filename)
93 logger.info("")
94
Gilles Peskineffaef812020-05-10 16:57:59 +020095BINARY_FILE_PATH_RE_LIST = [
96 r'docs/.*\.pdf\Z',
97 r'programs/fuzz/corpuses/[^.]+\Z',
98 r'tests/data_files/[^.]+\Z',
99 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
100 r'tests/data_files/.*\.req\.[^/]+\Z',
101 r'tests/data_files/.*malformed[^/]+\Z',
102 r'tests/data_files/format_pkcs12\.fmt\Z',
103]
104BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
105
Gilles Peskined5240ec2019-02-25 20:59:05 +0100106class LineIssueTracker(FileIssueTracker):
107 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000108
Gilles Peskined5240ec2019-02-25 20:59:05 +0100109 To implement a checker that processes files line by line, inherit from
110 this class and implement `line_with_issue`.
111 """
112
Gilles Peskineffaef812020-05-10 16:57:59 +0200113 # Exclude binary files.
114 path_exemptions = BINARY_FILE_PATH_RE
115
Gilles Peskined5240ec2019-02-25 20:59:05 +0100116 def issue_with_line(self, line, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100117 """Check the specified line for the issue that this class is for.
118
119 Subclasses must implement this method.
120 """
Gilles Peskined5240ec2019-02-25 20:59:05 +0100121 raise NotImplementedError
122
123 def check_file_line(self, filepath, line, line_number):
124 if self.issue_with_line(line, filepath):
125 self.record_issue(filepath, line_number)
126
127 def check_file_for_issue(self, filepath):
Gilles Peskineaf67f8d2020-03-24 16:49:21 +0100128 """Check the lines of the specified file.
129
130 Subclasses must implement the ``issue_with_line`` method.
131 """
Gilles Peskined5240ec2019-02-25 20:59:05 +0100132 with open(filepath, "rb") as f:
133 for i, line in enumerate(iter(f.readline, b"")):
134 self.check_file_line(filepath, line, i + 1)
135
Gilles Peskinececc7262020-03-24 22:26:01 +0100136
137def is_windows_file(filepath):
138 _root, ext = os.path.splitext(filepath)
Gilles Peskine7c8c9c92020-04-26 00:33:13 +0200139 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskinececc7262020-03-24 22:26:01 +0100140
141
Gilles Peskined5240ec2019-02-25 20:59:05 +0100142class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100143 """Track files with bad permissions.
144
145 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000146
Gilles Peskine21e85f72019-02-25 21:10:04 +0100147 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000148
149 def check_file_for_issue(self, filepath):
Gilles Peskine6fc52152019-02-25 21:24:27 +0100150 is_executable = os.access(filepath, os.X_OK)
151 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
152 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000153 self.files_with_issues[filepath] = None
154
155
Gilles Peskined5240ec2019-02-25 20:59:05 +0100156class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100157 """Track files that end with an incomplete line
158 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000159
Gilles Peskine21e85f72019-02-25 21:10:04 +0100160 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000161
Gilles Peskineffaef812020-05-10 16:57:59 +0200162 path_exemptions = BINARY_FILE_PATH_RE
163
Darryl Green10d9ce32018-02-28 10:02:55 +0000164 def check_file_for_issue(self, filepath):
165 with open(filepath, "rb") as f:
166 if not f.read().endswith(b"\n"):
167 self.files_with_issues[filepath] = None
168
169
Gilles Peskined5240ec2019-02-25 20:59:05 +0100170class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100171 """Track files that start with a UTF-8 BOM.
172 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000173
Gilles Peskine21e85f72019-02-25 21:10:04 +0100174 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000175
Gilles Peskinee856ba12020-05-10 16:52:44 +0200176 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskineffaef812020-05-10 16:57:59 +0200177 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskinececc7262020-03-24 22:26:01 +0100178
Darryl Green10d9ce32018-02-28 10:02:55 +0000179 def check_file_for_issue(self, filepath):
180 with open(filepath, "rb") as f:
181 if f.read().startswith(codecs.BOM_UTF8):
182 self.files_with_issues[filepath] = None
183
184
Gilles Peskinececc7262020-03-24 22:26:01 +0100185class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100186 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000187
Gilles Peskinececc7262020-03-24 22:26:01 +0100188 heading = "Non-Unix line endings:"
189
190 def should_check_file(self, filepath):
Gilles Peskinee6f1f242020-05-10 16:57:16 +0200191 if not super().should_check_file(filepath):
192 return False
Gilles Peskinececc7262020-03-24 22:26:01 +0100193 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000194
Gilles Peskined5240ec2019-02-25 20:59:05 +0100195 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000196 return b"\r" in line
197
198
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100199class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine368ccd42020-04-01 13:35:46 +0200200 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100201
202 heading = "Non-Windows line endings:"
203
204 def should_check_file(self, filepath):
Gilles Peskinee6f1f242020-05-10 16:57:16 +0200205 if not super().should_check_file(filepath):
206 return False
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100207 return is_windows_file(filepath)
208
209 def issue_with_line(self, line, _filepath):
Gilles Peskine368ccd42020-04-01 13:35:46 +0200210 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100211
212
Gilles Peskined5240ec2019-02-25 20:59:05 +0100213class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100214 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000215
Gilles Peskine21e85f72019-02-25 21:10:04 +0100216 heading = "Trailing whitespace:"
Gilles Peskinee856ba12020-05-10 16:52:44 +0200217 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000218
Gilles Peskined5240ec2019-02-25 20:59:05 +0100219 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000220 return line.rstrip(b"\r\n") != line.rstrip()
221
222
Gilles Peskined5240ec2019-02-25 20:59:05 +0100223class TabIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100224 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000225
Gilles Peskine21e85f72019-02-25 21:10:04 +0100226 heading = "Tabs present:"
Gilles Peskinee856ba12020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([
Gilles Peskinececc7262020-03-24 22:26:01 +0100228 ".sln",
Gilles Peskined69f51b2020-03-24 22:01:28 +0100229 "/Makefile",
230 "/generate_visualc_files.pl",
Gilles Peskine21e85f72019-02-25 21:10:04 +0100231 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000232
Gilles Peskined5240ec2019-02-25 20:59:05 +0100233 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000234 return b"\t" in line
235
236
Gilles Peskined5240ec2019-02-25 20:59:05 +0100237class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100238 """Track lines with merge artifacts.
239 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100240
Gilles Peskine21e85f72019-02-25 21:10:04 +0100241 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100242
Gilles Peskined5240ec2019-02-25 20:59:05 +0100243 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100244 # Detect leftover git conflict markers.
245 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
246 return True
247 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
248 return True
249 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskined5240ec2019-02-25 20:59:05 +0100250 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100251 return True
252 return False
253
Darryl Green10d9ce32018-02-28 10:02:55 +0000254
Gilles Peskine5d1dfd42020-03-24 18:25:17 +0100255class IntegrityChecker:
Gilles Peskine76605492019-02-25 20:35:31 +0100256 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000257
258 def __init__(self, log_file):
Gilles Peskine76605492019-02-25 20:35:31 +0100259 """Instantiate the sanity checker.
260 Check files under the current directory.
261 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000262 self.check_repo_path()
263 self.logger = None
264 self.setup_logger(log_file)
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100265 self.excluded_directories = [
266 '.git',
267 'mbed-os',
268 ]
Gilles Peskine95c55752018-09-28 11:48:10 +0200269 self.excluded_paths = list(map(os.path.normpath, [
270 'cov-int',
271 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200272 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000273 self.issues_to_check = [
274 PermissionIssueTracker(),
275 EndOfFileNewlineIssueTracker(),
276 Utf8BomIssueTracker(),
Gilles Peskinececc7262020-03-24 22:26:01 +0100277 UnixLineEndingIssueTracker(),
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100278 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000279 TrailingWhitespaceIssueTracker(),
280 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100281 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000282 ]
283
Gilles Peskine76605492019-02-25 20:35:31 +0100284 @staticmethod
285 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000286 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
287 raise Exception("Must be run from Mbed TLS root")
288
289 def setup_logger(self, log_file, level=logging.INFO):
290 self.logger = logging.getLogger()
291 self.logger.setLevel(level)
292 if log_file:
293 handler = logging.FileHandler(log_file)
294 self.logger.addHandler(handler)
295 else:
296 console = logging.StreamHandler()
297 self.logger.addHandler(console)
298
Gilles Peskine95c55752018-09-28 11:48:10 +0200299 def prune_branch(self, root, d):
300 if d in self.excluded_directories:
301 return True
302 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
303 return True
304 return False
305
Darryl Green10d9ce32018-02-28 10:02:55 +0000306 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200307 for root, dirs, files in os.walk("."):
308 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000309 for filename in sorted(files):
310 filepath = os.path.join(root, filename)
Darryl Green10d9ce32018-02-28 10:02:55 +0000311 for issue_to_check in self.issues_to_check:
312 if issue_to_check.should_check_file(filepath):
313 issue_to_check.check_file_for_issue(filepath)
314
315 def output_issues(self):
316 integrity_return_code = 0
317 for issue_to_check in self.issues_to_check:
318 if issue_to_check.files_with_issues:
319 integrity_return_code = 1
320 issue_to_check.output_file_issues(self.logger)
321 return integrity_return_code
322
323
324def run_main():
Gilles Peskine79cfef02019-07-04 19:31:02 +0200325 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000326 parser.add_argument(
327 "-l", "--log_file", type=str, help="path to optional output log",
328 )
329 check_args = parser.parse_args()
330 integrity_check = IntegrityChecker(check_args.log_file)
331 integrity_check.check_files()
332 return_code = integrity_check.output_issues()
333 sys.exit(return_code)
334
335
336if __name__ == "__main__":
337 run_main()