blob: 64c314392c1404d3dbca641dc5c2a9f5e9f10f5a [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úti4e9f7122020-06-05 13:02:18 +02004# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5#
6# This file is provided under the Apache License 2.0, or the
7# GNU General Public License v2.0 or later.
8#
9# **********
10# Apache License 2.0:
Bence Szépkúti09b4f192020-05-26 01:54:15 +020011#
12# Licensed under the Apache License, Version 2.0 (the "License"); you may
13# not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
20# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
23#
Bence Szépkúti4e9f7122020-06-05 13:02:18 +020024# **********
25#
26# **********
27# GNU General Public License v2.0 or later:
28#
29# This program is free software; you can redistribute it and/or modify
30# it under the terms of the GNU General Public License as published by
31# the Free Software Foundation; either version 2 of the License, or
32# (at your option) any later version.
33#
34# This program is distributed in the hope that it will be useful,
35# but WITHOUT ANY WARRANTY; without even the implied warranty of
36# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37# GNU General Public License for more details.
38#
39# You should have received a copy of the GNU General Public License along
40# with this program; if not, write to the Free Software Foundation, Inc.,
41# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
42#
43# **********
44#
Bence Szépkúti09b4f192020-05-26 01:54:15 +020045# This file is part of Mbed TLS (https://tls.mbed.org)
Gilles Peskine081daf02019-07-04 19:31:02 +020046
Darryl Greenda02eb32018-02-28 10:02:55 +000047"""
Darryl Greenda02eb32018-02-28 10:02:55 +000048This script checks the current state of the source code for minor issues,
49including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine570f7a22019-07-04 19:31:33 +020050trailing whitespace, and presence of UTF-8 BOM.
Darryl Greenda02eb32018-02-28 10:02:55 +000051Note: requires python 3, must be run from Mbed TLS root.
52"""
53
54import os
55import argparse
56import logging
57import codecs
Gilles Peskineb4805ec2020-05-10 16:57:16 +020058import re
Gilles Peskine4bda3252020-05-10 17:18:06 +020059import subprocess
Darryl Greenda02eb32018-02-28 10:02:55 +000060import sys
61
62
Gilles Peskineb5847d22020-03-24 18:25:17 +010063class FileIssueTracker:
Gilles Peskine7194ecb2019-02-25 20:59:05 +010064 """Base class for file-wide issue tracking.
65
66 To implement a checker that processes a file as a whole, inherit from
Gilles Peskinefb8c3732019-02-25 21:10:04 +010067 this class and implement `check_file_for_issue` and define ``heading``.
68
Gilles Peskine45137612020-05-10 16:52:44 +020069 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskinefb8c3732019-02-25 21:10:04 +010070 will not be checked.
71
Gilles Peskineb4805ec2020-05-10 16:57:16 +020072 ``path_exemptions``: files whose path (relative to the root of the source
73 tree) matches this regular expression will not be checked. This can be
74 ``None`` to match no path. Paths are normalized and converted to ``/``
75 separators before matching.
76
Gilles Peskinefb8c3732019-02-25 21:10:04 +010077 ``heading``: human-readable description of the issue
Gilles Peskine7194ecb2019-02-25 20:59:05 +010078 """
Darryl Greenda02eb32018-02-28 10:02:55 +000079
Gilles Peskine45137612020-05-10 16:52:44 +020080 suffix_exemptions = frozenset()
Gilles Peskineb4805ec2020-05-10 16:57:16 +020081 path_exemptions = None
Gilles Peskinefb8c3732019-02-25 21:10:04 +010082 # heading must be defined in derived classes.
83 # pylint: disable=no-member
84
Darryl Greenda02eb32018-02-28 10:02:55 +000085 def __init__(self):
Darryl Greenda02eb32018-02-28 10:02:55 +000086 self.files_with_issues = {}
87
Gilles Peskineb4805ec2020-05-10 16:57:16 +020088 @staticmethod
89 def normalize_path(filepath):
Gilles Peskine14b559a2020-05-28 18:19:20 +020090 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskineb4805ec2020-05-10 16:57:16 +020091 filepath = os.path.normpath(filepath)
Gilles Peskine14b559a2020-05-28 18:19:20 +020092 # On Windows, we may have backslashes to separate directories.
93 # We need slashes to match exemption lists.
Gilles Peskineb4805ec2020-05-10 16:57:16 +020094 seps = os.path.sep
95 if os.path.altsep is not None:
96 seps += os.path.altsep
97 return '/'.join(filepath.split(seps))
98
Darryl Greenda02eb32018-02-28 10:02:55 +000099 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100100 """Whether the given file name should be checked.
101
Gilles Peskine45137612020-05-10 16:52:44 +0200102 Files whose name ends with a string listed in ``self.suffix_exemptions``
103 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskine558e26d2020-03-24 16:49:21 +0100104 """
Gilles Peskine45137612020-05-10 16:52:44 +0200105 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +0000106 if filepath.endswith(files_exemption):
107 return False
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200108 if self.path_exemptions and \
109 re.match(self.path_exemptions, self.normalize_path(filepath)):
110 return False
Darryl Greenda02eb32018-02-28 10:02:55 +0000111 return True
112
Darryl Greenda02eb32018-02-28 10:02:55 +0000113 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100114 """Check the specified file for the issue that this class is for.
115
116 Subclasses must implement this method.
117 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100118 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +0000119
Gilles Peskine232fae32018-11-23 21:11:30 +0100120 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100121 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-11-23 21:11:30 +0100122 if filepath not in self.files_with_issues.keys():
123 self.files_with_issues[filepath] = []
124 self.files_with_issues[filepath].append(line_number)
125
Darryl Greenda02eb32018-02-28 10:02:55 +0000126 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100127 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000128 if self.files_with_issues.values():
129 logger.info(self.heading)
130 for filename, lines in sorted(self.files_with_issues.items()):
131 if lines:
132 logger.info("{}: {}".format(
133 filename, ", ".join(str(x) for x in lines)
134 ))
135 else:
136 logger.info(filename)
137 logger.info("")
138
Gilles Peskine986a06d2020-05-10 16:57:59 +0200139BINARY_FILE_PATH_RE_LIST = [
140 r'docs/.*\.pdf\Z',
141 r'programs/fuzz/corpuses/[^.]+\Z',
142 r'tests/data_files/[^.]+\Z',
143 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
144 r'tests/data_files/.*\.req\.[^/]+\Z',
145 r'tests/data_files/.*malformed[^/]+\Z',
146 r'tests/data_files/format_pkcs12\.fmt\Z',
147]
148BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
149
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100150class LineIssueTracker(FileIssueTracker):
151 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +0000152
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100153 To implement a checker that processes files line by line, inherit from
154 this class and implement `line_with_issue`.
155 """
156
Gilles Peskine986a06d2020-05-10 16:57:59 +0200157 # Exclude binary files.
158 path_exemptions = BINARY_FILE_PATH_RE
159
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100160 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100161 """Check the specified line for the issue that this class is for.
162
163 Subclasses must implement this method.
164 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100165 raise NotImplementedError
166
167 def check_file_line(self, filepath, line, line_number):
168 if self.issue_with_line(line, filepath):
169 self.record_issue(filepath, line_number)
170
171 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100172 """Check the lines of the specified file.
173
174 Subclasses must implement the ``issue_with_line`` method.
175 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100176 with open(filepath, "rb") as f:
177 for i, line in enumerate(iter(f.readline, b"")):
178 self.check_file_line(filepath, line, i + 1)
179
Gilles Peskine227dfd42020-03-24 22:26:01 +0100180
181def is_windows_file(filepath):
182 _root, ext = os.path.splitext(filepath)
Gilles Peskinee7e149f2020-05-10 17:36:51 +0200183 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100184
185
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100186class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100187 """Track files with bad permissions.
188
189 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000190
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100191 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000192
193 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +0100194 is_executable = os.access(filepath, os.X_OK)
195 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
196 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000197 self.files_with_issues[filepath] = None
198
199
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100200class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100201 """Track files that end with an incomplete line
202 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000203
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100204 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000205
Gilles Peskine986a06d2020-05-10 16:57:59 +0200206 path_exemptions = BINARY_FILE_PATH_RE
207
Darryl Greenda02eb32018-02-28 10:02:55 +0000208 def check_file_for_issue(self, filepath):
209 with open(filepath, "rb") as f:
Gilles Peskinebe76c192020-05-10 17:36:42 +0200210 try:
211 f.seek(-1, 2)
212 except OSError:
213 # This script only works on regular files. If we can't seek
214 # 1 before the end, it means that this position is before
215 # the beginning of the file, i.e. that the file is empty.
216 return
217 if f.read(1) != b"\n":
Darryl Greenda02eb32018-02-28 10:02:55 +0000218 self.files_with_issues[filepath] = None
219
220
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100221class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100222 """Track files that start with a UTF-8 BOM.
223 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000224
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100225 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000226
Gilles Peskine45137612020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine986a06d2020-05-10 16:57:59 +0200228 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine227dfd42020-03-24 22:26:01 +0100229
Darryl Greenda02eb32018-02-28 10:02:55 +0000230 def check_file_for_issue(self, filepath):
231 with open(filepath, "rb") as f:
232 if f.read().startswith(codecs.BOM_UTF8):
233 self.files_with_issues[filepath] = None
234
235
Gilles Peskine227dfd42020-03-24 22:26:01 +0100236class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100237 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000238
Gilles Peskine227dfd42020-03-24 22:26:01 +0100239 heading = "Non-Unix line endings:"
240
241 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200242 if not super().should_check_file(filepath):
243 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100244 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000245
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100246 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000247 return b"\r" in line
248
249
Gilles Peskine783da632020-03-24 22:29:11 +0100250class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200251 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100252
253 heading = "Non-Windows line endings:"
254
255 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200256 if not super().should_check_file(filepath):
257 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100258 return is_windows_file(filepath)
259
260 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200261 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100262
263
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100264class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100265 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000266
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100267 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200268 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000269
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100270 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000271 return line.rstrip(b"\r\n") != line.rstrip()
272
273
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100274class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100275 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000276
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100277 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200278 suffix_exemptions = frozenset([
Gilles Peskine8fa5be52020-05-10 17:37:02 +0200279 ".pem", # some openssl dumps have tabs
Gilles Peskine227dfd42020-03-24 22:26:01 +0100280 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100281 "/Makefile",
282 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100283 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000284
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100285 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000286 return b"\t" in line
287
288
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100289class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100290 """Track lines with merge artifacts.
291 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100292
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100293 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100294
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100295 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100296 # Detect leftover git conflict markers.
297 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
298 return True
299 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
300 return True
301 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100302 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100303 return True
304 return False
305
Darryl Greenda02eb32018-02-28 10:02:55 +0000306
Gilles Peskineb5847d22020-03-24 18:25:17 +0100307class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100308 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000309
310 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100311 """Instantiate the sanity checker.
312 Check files under the current directory.
313 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000314 self.check_repo_path()
315 self.logger = None
316 self.setup_logger(log_file)
Darryl Greenda02eb32018-02-28 10:02:55 +0000317 self.issues_to_check = [
318 PermissionIssueTracker(),
319 EndOfFileNewlineIssueTracker(),
320 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100321 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100322 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000323 TrailingWhitespaceIssueTracker(),
324 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100325 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000326 ]
327
Gilles Peskine4fb66782019-02-25 20:35:31 +0100328 @staticmethod
329 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000330 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
331 raise Exception("Must be run from Mbed TLS root")
332
333 def setup_logger(self, log_file, level=logging.INFO):
334 self.logger = logging.getLogger()
335 self.logger.setLevel(level)
336 if log_file:
337 handler = logging.FileHandler(log_file)
338 self.logger.addHandler(handler)
339 else:
340 console = logging.StreamHandler()
341 self.logger.addHandler(console)
342
Gilles Peskine4bda3252020-05-10 17:18:06 +0200343 @staticmethod
344 def collect_files():
345 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
346 bytes_filepaths = bytes_output.split(b'\0')[:-1]
347 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
348 # Prepend './' to files in the top-level directory so that
349 # something like `'/Makefile' in fp` matches in the top-level
350 # directory as well as in subdirectories.
351 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
352 for fp in ascii_filepaths]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200353
Darryl Greenda02eb32018-02-28 10:02:55 +0000354 def check_files(self):
Gilles Peskine4bda3252020-05-10 17:18:06 +0200355 for issue_to_check in self.issues_to_check:
356 for filepath in self.collect_files():
357 if issue_to_check.should_check_file(filepath):
358 issue_to_check.check_file_for_issue(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000359
360 def output_issues(self):
361 integrity_return_code = 0
362 for issue_to_check in self.issues_to_check:
363 if issue_to_check.files_with_issues:
364 integrity_return_code = 1
365 issue_to_check.output_file_issues(self.logger)
366 return integrity_return_code
367
368
369def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200370 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000371 parser.add_argument(
372 "-l", "--log_file", type=str, help="path to optional output log",
373 )
374 check_args = parser.parse_args()
375 integrity_check = IntegrityChecker(check_args.log_file)
376 integrity_check.check_files()
377 return_code = integrity_check.output_issues()
378 sys.exit(return_code)
379
380
381if __name__ == "__main__":
382 run_main()