blob: c2288432ce14d7b8f6c1f44475130ba2a4e1c7d4 [file] [log] [blame]
Darryl Green7c2dd582018-03-01 14:53:49 +00001#!/usr/bin/env python3
Gilles Peskine4b9f7a22022-06-20 18:51:18 +02002"""This script compares the interfaces of two versions of Mbed TLS, looking
Gilles Peskinecfd4fae2021-04-23 16:37:12 +02003for backward incompatibilities between two different Git revisions within
4an Mbed TLS repository. It must be run from the root of a Git working tree.
5
Gilles Peskinef4be01f2022-06-20 18:51:44 +02006### How the script works ###
7
Gilles Peskinecfd4fae2021-04-23 16:37:12 +02008For the source (API) and runtime (ABI) interface compatibility, this script
9is a small wrapper around the abi-compliance-checker and abi-dumper tools,
10applying them to compare the header and library files.
11
12For the storage format, this script compares the automatically generated
Gilles Peskine2eae8d72022-02-22 19:02:44 +010013storage tests and the manual read tests, and complains if there is a
Gilles Peskine1177f372022-03-04 19:59:55 +010014reduction in coverage. A change in test data will be signaled as a
Gilles Peskine2eae8d72022-02-22 19:02:44 +010015coverage reduction since the old test data is no longer present. A change in
Gilles Peskine1177f372022-03-04 19:59:55 +010016how test data is presented will be signaled as well; this would be a false
Gilles Peskine2eae8d72022-02-22 19:02:44 +010017positive.
Gilles Peskinecfd4fae2021-04-23 16:37:12 +020018
Gilles Peskine2eae8d72022-02-22 19:02:44 +010019The results of the API/ABI comparison are either formatted as HTML and stored
20at a configurable location, or are given as a brief list of problems.
21Returns 0 on success, 1 on non-compliance, and 2 if there is an error
Gilles Peskinecfd4fae2021-04-23 16:37:12 +020022while running the script.
Gilles Peskine56354592022-03-03 10:23:09 +010023
Gilles Peskinef4be01f2022-06-20 18:51:44 +020024### How to interpret non-compliance ###
25
26This script has relatively common false positives. In many scenarios, it only
27reports a pass if there is a strict textual match between the old version and
28the new version, and it reports problems where there is a sufficient semantic
29match but not a textual match. This section lists some common false positives.
30This is not an exhaustive list: in the end what matters is whether we are
31breaking a backward compatibility goal.
32
33**API**: the goal is that if an application works with the old version of the
34library, it can be recompiled against the new version and will still work.
35This is normally validated by comparing the declarations in `include/*/*.h`.
36A failure is a declaration that has disappeared or that now has a different
37type.
38
39 * It's ok to change or remove macros and functions that are documented as
40 for internal use only or as experimental.
41 * It's ok to rename function or macro parameters as long as the semantics
42 has not changed.
43 * It's ok to change or remove structure fields that are documented as
44 private.
45 * It's ok to add fields to a structure that already had private fields
46 or was documented as extensible.
47
48**ABI**: the goal is that if an application was built against the old version
49of the library, the same binary will work when linked against the new version.
50This is normally validated by comparing the symbols exported by `libmbed*.so`.
51A failure is a symbol that is no longer exported by the same library or that
52now has a different type.
53
54 * All ABI changes are acceptable if the library version is bumped
55 (see `scripts/bump_version.sh`).
56 * ABI changes that concern functions which are declared only inside the
57 library directory, and not in `include/*/*.h`, are acceptable only if
58 the function was only ever used inside the same library (libmbedcrypto,
59 libmbedx509, libmbedtls). As a counter example, if the old version
60 of libmbedtls calls mbedtls_foo() from libmbedcrypto, and the new version
61 of libmbedcrypto no longer has a compatible mbedtls_foo(), this does
62 require a version bump for libmbedcrypto.
63
64**Storage format**: the goal is to check that persistent keys stored by the
65old version can be read by the new version. This is normally validated by
66comparing the `*read*` test cases in `test_suite*storage_format*.data`.
67A failure is a storage read test case that is no longer present with the same
68function name and parameter list.
69
70 * It's ok if the same test data is present, but its presentation has changed,
71 for example if a test function is renamed or has different parameters.
72 * It's ok if redundant tests are removed.
73
74**Generated test coverage**: the goal is to check that automatically
75generated tests have as much coverage as before. This is normally validated
76by comparing the test cases that are automatically generated by a script.
77A failure is a generated test case that is no longer present with the same
78function name and parameter list.
79
80 * It's ok if the same test data is present, but its presentation has changed,
81 for example if a test function is renamed or has different parameters.
82 * It's ok if redundant tests are removed.
83
Darryl Green78696802018-04-06 11:23:22 +010084"""
Darryl Green7c2dd582018-03-01 14:53:49 +000085
Bence Szépkúti1e148272020-08-07 13:07:28 +020086# Copyright The Mbed TLS Contributors
Bence Szépkútic7da1fe2020-05-26 01:54:15 +020087# SPDX-License-Identifier: Apache-2.0
88#
89# Licensed under the Apache License, Version 2.0 (the "License"); you may
90# not use this file except in compliance with the License.
91# You may obtain a copy of the License at
92#
93# http://www.apache.org/licenses/LICENSE-2.0
94#
95# Unless required by applicable law or agreed to in writing, software
96# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
97# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
98# See the License for the specific language governing permissions and
99# limitations under the License.
Bence Szépkútic7da1fe2020-05-26 01:54:15 +0200100
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100101import glob
Darryl Green7c2dd582018-03-01 14:53:49 +0000102import os
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200103import re
Darryl Green7c2dd582018-03-01 14:53:49 +0000104import sys
105import traceback
106import shutil
107import subprocess
108import argparse
109import logging
110import tempfile
Darryl Green9f357d62019-02-25 11:35:05 +0000111import fnmatch
Darryl Green0d1ca512019-04-09 09:14:17 +0100112from types import SimpleNamespace
Darryl Green7c2dd582018-03-01 14:53:49 +0000113
Darryl Greene62f9bb2019-02-21 13:09:26 +0000114import xml.etree.ElementTree as ET
115
Darryl Green7c2dd582018-03-01 14:53:49 +0000116
Gilles Peskine184c0962020-03-24 18:25:17 +0100117class AbiChecker:
Gilles Peskine712afa72019-02-25 20:36:52 +0100118 """API and ABI checker."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000119
Darryl Green0d1ca512019-04-09 09:14:17 +0100120 def __init__(self, old_version, new_version, configuration):
Gilles Peskine712afa72019-02-25 20:36:52 +0100121 """Instantiate the API/ABI checker.
122
Darryl Green7c1a7332019-03-05 16:25:38 +0000123 old_version: RepoVersion containing details to compare against
124 new_version: RepoVersion containing details to check
Darryl Greenf67e3492019-04-12 15:17:02 +0100125 configuration.report_dir: directory for output files
126 configuration.keep_all_reports: if false, delete old reports
127 configuration.brief: if true, output shorter report to stdout
Gilles Peskine1177f372022-03-04 19:59:55 +0100128 configuration.check_abi: if true, compare ABIs
Gilles Peskine793778f2021-04-23 16:32:32 +0200129 configuration.check_api: if true, compare APIs
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200130 configuration.check_storage: if true, compare storage format tests
Darryl Greenf67e3492019-04-12 15:17:02 +0100131 configuration.skip_file: path to file containing symbols and types to skip
Gilles Peskine712afa72019-02-25 20:36:52 +0100132 """
Darryl Green7c2dd582018-03-01 14:53:49 +0000133 self.repo_path = "."
134 self.log = None
Darryl Green0d1ca512019-04-09 09:14:17 +0100135 self.verbose = configuration.verbose
Darryl Green3a5f6c82019-03-05 16:30:39 +0000136 self._setup_logger()
Darryl Green0d1ca512019-04-09 09:14:17 +0100137 self.report_dir = os.path.abspath(configuration.report_dir)
138 self.keep_all_reports = configuration.keep_all_reports
Darryl Green492bc402019-04-11 15:50:41 +0100139 self.can_remove_report_dir = not (os.path.exists(self.report_dir) or
Darryl Green0d1ca512019-04-09 09:14:17 +0100140 self.keep_all_reports)
Darryl Green7c1a7332019-03-05 16:25:38 +0000141 self.old_version = old_version
142 self.new_version = new_version
Darryl Green0d1ca512019-04-09 09:14:17 +0100143 self.skip_file = configuration.skip_file
Gilles Peskine793778f2021-04-23 16:32:32 +0200144 self.check_abi = configuration.check_abi
145 self.check_api = configuration.check_api
146 if self.check_abi != self.check_api:
147 raise Exception('Checking API without ABI or vice versa is not supported')
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200148 self.check_storage_tests = configuration.check_storage
Darryl Green0d1ca512019-04-09 09:14:17 +0100149 self.brief = configuration.brief
Darryl Green7c2dd582018-03-01 14:53:49 +0000150 self.git_command = "git"
151 self.make_command = "make"
152
Gilles Peskine712afa72019-02-25 20:36:52 +0100153 @staticmethod
154 def check_repo_path():
Gilles Peskine6aa32cc2019-07-04 18:59:36 +0200155 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
Darryl Green7c2dd582018-03-01 14:53:49 +0000156 raise Exception("Must be run from Mbed TLS root")
157
Darryl Green3a5f6c82019-03-05 16:30:39 +0000158 def _setup_logger(self):
Darryl Green7c2dd582018-03-01 14:53:49 +0000159 self.log = logging.getLogger()
Darryl Green3c3da792019-03-08 11:30:04 +0000160 if self.verbose:
161 self.log.setLevel(logging.DEBUG)
162 else:
163 self.log.setLevel(logging.INFO)
Darryl Green7c2dd582018-03-01 14:53:49 +0000164 self.log.addHandler(logging.StreamHandler())
165
Gilles Peskine712afa72019-02-25 20:36:52 +0100166 @staticmethod
167 def check_abi_tools_are_installed():
Darryl Green7c2dd582018-03-01 14:53:49 +0000168 for command in ["abi-dumper", "abi-compliance-checker"]:
169 if not shutil.which(command):
170 raise Exception("{} not installed, aborting".format(command))
171
Darryl Green3a5f6c82019-03-05 16:30:39 +0000172 def _get_clean_worktree_for_git_revision(self, version):
Darryl Green7c1a7332019-03-05 16:25:38 +0000173 """Make a separate worktree with version.revision checked out.
Gilles Peskine712afa72019-02-25 20:36:52 +0100174 Do not modify the current worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000175 git_worktree_path = tempfile.mkdtemp()
Darryl Green7c1a7332019-03-05 16:25:38 +0000176 if version.repository:
Darryl Green3c3da792019-03-08 11:30:04 +0000177 self.log.debug(
Darryl Greenda84e322019-02-19 16:59:33 +0000178 "Checking out git worktree for revision {} from {}".format(
Darryl Green7c1a7332019-03-05 16:25:38 +0000179 version.revision, version.repository
Darryl Greenda84e322019-02-19 16:59:33 +0000180 )
181 )
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100182 fetch_output = subprocess.check_output(
Darryl Green7c1a7332019-03-05 16:25:38 +0000183 [self.git_command, "fetch",
184 version.repository, version.revision],
Darryl Greenda84e322019-02-19 16:59:33 +0000185 cwd=self.repo_path,
Darryl Greenda84e322019-02-19 16:59:33 +0000186 stderr=subprocess.STDOUT
187 )
Darryl Green3c3da792019-03-08 11:30:04 +0000188 self.log.debug(fetch_output.decode("utf-8"))
Darryl Greenda84e322019-02-19 16:59:33 +0000189 worktree_rev = "FETCH_HEAD"
190 else:
Darryl Green3c3da792019-03-08 11:30:04 +0000191 self.log.debug("Checking out git worktree for revision {}".format(
Darryl Green7c1a7332019-03-05 16:25:38 +0000192 version.revision
193 ))
194 worktree_rev = version.revision
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100195 worktree_output = subprocess.check_output(
Darryl Greenda84e322019-02-19 16:59:33 +0000196 [self.git_command, "worktree", "add", "--detach",
197 git_worktree_path, worktree_rev],
Darryl Green7c2dd582018-03-01 14:53:49 +0000198 cwd=self.repo_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000199 stderr=subprocess.STDOUT
200 )
Darryl Green3c3da792019-03-08 11:30:04 +0000201 self.log.debug(worktree_output.decode("utf-8"))
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200202 version.commit = subprocess.check_output(
Darryl Green762351b2019-07-25 14:33:33 +0100203 [self.git_command, "rev-parse", "HEAD"],
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200204 cwd=git_worktree_path,
205 stderr=subprocess.STDOUT
206 ).decode("ascii").rstrip()
207 self.log.debug("Commit is {}".format(version.commit))
Darryl Green7c2dd582018-03-01 14:53:49 +0000208 return git_worktree_path
209
Darryl Green3a5f6c82019-03-05 16:30:39 +0000210 def _update_git_submodules(self, git_worktree_path, version):
Darryl Green8184df52019-04-05 17:06:17 +0100211 """If the crypto submodule is present, initialize it.
212 if version.crypto_revision exists, update it to that revision,
213 otherwise update it to the default revision"""
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100214 update_output = subprocess.check_output(
Jaeden Ameroffeb1b82018-11-02 16:35:09 +0000215 [self.git_command, "submodule", "update", "--init", '--recursive'],
216 cwd=git_worktree_path,
Jaeden Ameroffeb1b82018-11-02 16:35:09 +0000217 stderr=subprocess.STDOUT
218 )
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100219 self.log.debug(update_output.decode("utf-8"))
Darryl Greene29ce702019-03-05 15:23:25 +0000220 if not (os.path.exists(os.path.join(git_worktree_path, "crypto"))
Darryl Green7c1a7332019-03-05 16:25:38 +0000221 and version.crypto_revision):
Darryl Greene29ce702019-03-05 15:23:25 +0000222 return
223
Darryl Green7c1a7332019-03-05 16:25:38 +0000224 if version.crypto_repository:
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100225 fetch_output = subprocess.check_output(
Darryl Green1d95c532019-03-08 11:12:19 +0000226 [self.git_command, "fetch", version.crypto_repository,
227 version.crypto_revision],
Darryl Greene29ce702019-03-05 15:23:25 +0000228 cwd=os.path.join(git_worktree_path, "crypto"),
Darryl Greene29ce702019-03-05 15:23:25 +0000229 stderr=subprocess.STDOUT
230 )
Darryl Green3c3da792019-03-08 11:30:04 +0000231 self.log.debug(fetch_output.decode("utf-8"))
Darryl Green1d95c532019-03-08 11:12:19 +0000232 crypto_rev = "FETCH_HEAD"
233 else:
234 crypto_rev = version.crypto_revision
235
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100236 checkout_output = subprocess.check_output(
Darryl Green1d95c532019-03-08 11:12:19 +0000237 [self.git_command, "checkout", crypto_rev],
238 cwd=os.path.join(git_worktree_path, "crypto"),
Darryl Green1d95c532019-03-08 11:12:19 +0000239 stderr=subprocess.STDOUT
240 )
Darryl Green3c3da792019-03-08 11:30:04 +0000241 self.log.debug(checkout_output.decode("utf-8"))
Jaeden Ameroffeb1b82018-11-02 16:35:09 +0000242
Darryl Green3a5f6c82019-03-05 16:30:39 +0000243 def _build_shared_libraries(self, git_worktree_path, version):
Gilles Peskine712afa72019-02-25 20:36:52 +0100244 """Build the shared libraries in the specified worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000245 my_environment = os.environ.copy()
246 my_environment["CFLAGS"] = "-g -Og"
247 my_environment["SHARED"] = "1"
Darryl Greend2dba362019-05-09 13:03:05 +0100248 if os.path.exists(os.path.join(git_worktree_path, "crypto")):
249 my_environment["USE_CRYPTO_SUBMODULE"] = "1"
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100250 make_output = subprocess.check_output(
Darryl Greenddf25a62019-02-28 11:52:39 +0000251 [self.make_command, "lib"],
Darryl Green7c2dd582018-03-01 14:53:49 +0000252 env=my_environment,
253 cwd=git_worktree_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000254 stderr=subprocess.STDOUT
255 )
Darryl Green3c3da792019-03-08 11:30:04 +0000256 self.log.debug(make_output.decode("utf-8"))
Darryl Greenf025d532019-04-12 15:18:02 +0100257 for root, _dirs, files in os.walk(git_worktree_path):
Darryl Green9f357d62019-02-25 11:35:05 +0000258 for file in fnmatch.filter(files, "*.so"):
Darryl Green7c1a7332019-03-05 16:25:38 +0000259 version.modules[os.path.splitext(file)[0]] = (
Darryl Green3e7a9802019-02-27 16:53:40 +0000260 os.path.join(root, file)
Darryl Green9f357d62019-02-25 11:35:05 +0000261 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000262
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200263 @staticmethod
264 def _pretty_revision(version):
265 if version.revision == version.commit:
266 return version.revision
267 else:
268 return "{} ({})".format(version.revision, version.commit)
269
Darryl Green8184df52019-04-05 17:06:17 +0100270 def _get_abi_dumps_from_shared_libraries(self, version):
Gilles Peskine712afa72019-02-25 20:36:52 +0100271 """Generate the ABI dumps for the specified git revision.
Darryl Green8184df52019-04-05 17:06:17 +0100272 The shared libraries must have been built and the module paths
273 present in version.modules."""
Darryl Green7c1a7332019-03-05 16:25:38 +0000274 for mbed_module, module_path in version.modules.items():
Darryl Green7c2dd582018-03-01 14:53:49 +0000275 output_path = os.path.join(
Darryl Greenfe9a6752019-04-04 14:39:33 +0100276 self.report_dir, "{}-{}-{}.dump".format(
277 mbed_module, version.revision, version.version
Darryl Green3e7a9802019-02-27 16:53:40 +0000278 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000279 )
280 abi_dump_command = [
281 "abi-dumper",
Darryl Green9f357d62019-02-25 11:35:05 +0000282 module_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000283 "-o", output_path,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200284 "-lver", self._pretty_revision(version),
Darryl Green7c2dd582018-03-01 14:53:49 +0000285 ]
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100286 abi_dump_output = subprocess.check_output(
Darryl Green7c2dd582018-03-01 14:53:49 +0000287 abi_dump_command,
Darryl Green7c2dd582018-03-01 14:53:49 +0000288 stderr=subprocess.STDOUT
289 )
Darryl Green3c3da792019-03-08 11:30:04 +0000290 self.log.debug(abi_dump_output.decode("utf-8"))
Darryl Green7c1a7332019-03-05 16:25:38 +0000291 version.abi_dumps[mbed_module] = output_path
Darryl Green7c2dd582018-03-01 14:53:49 +0000292
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200293 @staticmethod
294 def _normalize_storage_test_case_data(line):
295 """Eliminate cosmetic or irrelevant details in storage format test cases."""
296 line = re.sub(r'\s+', r'', line)
297 return line
298
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100299 def _read_storage_tests(self,
300 directory,
301 filename,
302 is_generated,
303 storage_tests):
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200304 """Record storage tests from the given file.
305
306 Populate the storage_tests dictionary with test cases read from
307 filename under directory.
308 """
309 at_paragraph_start = True
310 description = None
311 full_path = os.path.join(directory, filename)
Gilles Peskineaeb8d662022-03-04 20:02:00 +0100312 with open(full_path) as fd:
313 for line_number, line in enumerate(fd, 1):
314 line = line.strip()
315 if not line:
316 at_paragraph_start = True
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100317 continue
Gilles Peskineaeb8d662022-03-04 20:02:00 +0100318 if line.startswith('#'):
319 continue
320 if at_paragraph_start:
321 description = line.strip()
322 at_paragraph_start = False
323 continue
324 if line.startswith('depends_on:'):
325 continue
326 # We've reached a test case data line
327 test_case_data = self._normalize_storage_test_case_data(line)
328 if not is_generated:
329 # In manual test data, only look at read tests.
330 function_name = test_case_data.split(':', 1)[0]
331 if 'read' not in function_name.split('_'):
332 continue
333 metadata = SimpleNamespace(
334 filename=filename,
335 line_number=line_number,
336 description=description
337 )
338 storage_tests[test_case_data] = metadata
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200339
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100340 @staticmethod
341 def _list_generated_test_data_files(git_worktree_path):
342 """List the generated test data files."""
343 output = subprocess.check_output(
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200344 ['tests/scripts/generate_psa_tests.py', '--list'],
345 cwd=git_worktree_path,
346 ).decode('ascii')
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100347 return [line for line in output.split('\n') if line]
348
349 def _get_storage_format_tests(self, version, git_worktree_path):
350 """Record the storage format tests for the specified git version.
351
352 The storage format tests are the test suite data files whose name
353 contains "storage_format".
354
355 The version must be checked out at git_worktree_path.
356
357 This function creates or updates the generated data files.
358 """
359 # Existing test data files. This may be missing some automatically
360 # generated files if they haven't been generated yet.
361 storage_data_files = set(glob.glob(
362 'tests/suites/test_suite_*storage_format*.data'
363 ))
364 # Discover and (re)generate automatically generated data files.
365 to_be_generated = set()
366 for filename in self._list_generated_test_data_files(git_worktree_path):
367 if 'storage_format' in filename:
368 storage_data_files.add(filename)
369 to_be_generated.add(filename)
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200370 subprocess.check_call(
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100371 ['tests/scripts/generate_psa_tests.py'] + sorted(to_be_generated),
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200372 cwd=git_worktree_path,
373 )
Gilles Peskine2eae8d72022-02-22 19:02:44 +0100374 for test_file in sorted(storage_data_files):
375 self._read_storage_tests(git_worktree_path,
376 test_file,
377 test_file in to_be_generated,
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200378 version.storage_tests)
379
Darryl Green3a5f6c82019-03-05 16:30:39 +0000380 def _cleanup_worktree(self, git_worktree_path):
Gilles Peskine712afa72019-02-25 20:36:52 +0100381 """Remove the specified git worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000382 shutil.rmtree(git_worktree_path)
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100383 worktree_output = subprocess.check_output(
Darryl Green7c2dd582018-03-01 14:53:49 +0000384 [self.git_command, "worktree", "prune"],
385 cwd=self.repo_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000386 stderr=subprocess.STDOUT
387 )
Darryl Green3c3da792019-03-08 11:30:04 +0000388 self.log.debug(worktree_output.decode("utf-8"))
Darryl Green7c2dd582018-03-01 14:53:49 +0000389
Darryl Green3a5f6c82019-03-05 16:30:39 +0000390 def _get_abi_dump_for_ref(self, version):
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200391 """Generate the interface information for the specified git revision."""
Darryl Green3a5f6c82019-03-05 16:30:39 +0000392 git_worktree_path = self._get_clean_worktree_for_git_revision(version)
393 self._update_git_submodules(git_worktree_path, version)
Gilles Peskine793778f2021-04-23 16:32:32 +0200394 if self.check_abi:
395 self._build_shared_libraries(git_worktree_path, version)
396 self._get_abi_dumps_from_shared_libraries(version)
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200397 if self.check_storage_tests:
398 self._get_storage_format_tests(version, git_worktree_path)
Darryl Green3a5f6c82019-03-05 16:30:39 +0000399 self._cleanup_worktree(git_worktree_path)
Darryl Green7c2dd582018-03-01 14:53:49 +0000400
Darryl Green3a5f6c82019-03-05 16:30:39 +0000401 def _remove_children_with_tag(self, parent, tag):
Darryl Greene62f9bb2019-02-21 13:09:26 +0000402 children = parent.getchildren()
403 for child in children:
404 if child.tag == tag:
405 parent.remove(child)
406 else:
Darryl Green3a5f6c82019-03-05 16:30:39 +0000407 self._remove_children_with_tag(child, tag)
Darryl Greene62f9bb2019-02-21 13:09:26 +0000408
Darryl Green3a5f6c82019-03-05 16:30:39 +0000409 def _remove_extra_detail_from_report(self, report_root):
Darryl Greene62f9bb2019-02-21 13:09:26 +0000410 for tag in ['test_info', 'test_results', 'problem_summary',
Darryl Greenc6f874b2019-06-05 12:57:50 +0100411 'added_symbols', 'affected']:
Darryl Green3a5f6c82019-03-05 16:30:39 +0000412 self._remove_children_with_tag(report_root, tag)
Darryl Greene62f9bb2019-02-21 13:09:26 +0000413
414 for report in report_root:
415 for problems in report.getchildren()[:]:
416 if not problems.getchildren():
417 report.remove(problems)
418
Gilles Peskineada828f2019-07-04 19:17:40 +0200419 def _abi_compliance_command(self, mbed_module, output_path):
420 """Build the command to run to analyze the library mbed_module.
421 The report will be placed in output_path."""
422 abi_compliance_command = [
423 "abi-compliance-checker",
424 "-l", mbed_module,
425 "-old", self.old_version.abi_dumps[mbed_module],
426 "-new", self.new_version.abi_dumps[mbed_module],
427 "-strict",
428 "-report-path", output_path,
429 ]
430 if self.skip_file:
431 abi_compliance_command += ["-skip-symbols", self.skip_file,
432 "-skip-types", self.skip_file]
433 if self.brief:
434 abi_compliance_command += ["-report-format", "xml",
435 "-stdout"]
436 return abi_compliance_command
437
438 def _is_library_compatible(self, mbed_module, compatibility_report):
439 """Test if the library mbed_module has remained compatible.
440 Append a message regarding compatibility to compatibility_report."""
441 output_path = os.path.join(
442 self.report_dir, "{}-{}-{}.html".format(
443 mbed_module, self.old_version.revision,
444 self.new_version.revision
445 )
446 )
447 try:
448 subprocess.check_output(
449 self._abi_compliance_command(mbed_module, output_path),
450 stderr=subprocess.STDOUT
451 )
452 except subprocess.CalledProcessError as err:
453 if err.returncode != 1:
454 raise err
455 if self.brief:
456 self.log.info(
457 "Compatibility issues found for {}".format(mbed_module)
458 )
459 report_root = ET.fromstring(err.output.decode("utf-8"))
460 self._remove_extra_detail_from_report(report_root)
461 self.log.info(ET.tostring(report_root).decode("utf-8"))
462 else:
463 self.can_remove_report_dir = False
464 compatibility_report.append(
465 "Compatibility issues found for {}, "
466 "for details see {}".format(mbed_module, output_path)
467 )
468 return False
469 compatibility_report.append(
470 "No compatibility issues for {}".format(mbed_module)
471 )
472 if not (self.keep_all_reports or self.brief):
473 os.remove(output_path)
474 return True
475
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200476 @staticmethod
477 def _is_storage_format_compatible(old_tests, new_tests,
478 compatibility_report):
479 """Check whether all tests present in old_tests are also in new_tests.
480
481 Append a message regarding compatibility to compatibility_report.
482 """
483 missing = frozenset(old_tests.keys()).difference(new_tests.keys())
484 for test_data in sorted(missing):
485 metadata = old_tests[test_data]
486 compatibility_report.append(
487 'Test case from {} line {} "{}" has disappeared: {}'.format(
488 metadata.filename, metadata.line_number,
489 metadata.description, test_data
490 )
491 )
492 compatibility_report.append(
493 'FAIL: {}/{} storage format test cases have changed or disappeared.'.format(
494 len(missing), len(old_tests)
495 ) if missing else
496 'PASS: All {} storage format test cases are preserved.'.format(
497 len(old_tests)
498 )
499 )
500 compatibility_report.append(
501 'Info: number of storage format tests cases: {} -> {}.'.format(
502 len(old_tests), len(new_tests)
503 )
504 )
505 return not missing
506
Darryl Green7c2dd582018-03-01 14:53:49 +0000507 def get_abi_compatibility_report(self):
Gilles Peskine712afa72019-02-25 20:36:52 +0100508 """Generate a report of the differences between the reference ABI
Darryl Green8184df52019-04-05 17:06:17 +0100509 and the new ABI. ABI dumps from self.old_version and self.new_version
510 must be available."""
Gilles Peskineada828f2019-07-04 19:17:40 +0200511 compatibility_report = ["Checking evolution from {} to {}".format(
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200512 self._pretty_revision(self.old_version),
513 self._pretty_revision(self.new_version)
Gilles Peskineada828f2019-07-04 19:17:40 +0200514 )]
Darryl Green7c2dd582018-03-01 14:53:49 +0000515 compliance_return_code = 0
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200516
Gilles Peskine793778f2021-04-23 16:32:32 +0200517 if self.check_abi:
518 shared_modules = list(set(self.old_version.modules.keys()) &
519 set(self.new_version.modules.keys()))
520 for mbed_module in shared_modules:
521 if not self._is_library_compatible(mbed_module,
522 compatibility_report):
523 compliance_return_code = 1
524
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200525 if self.check_storage_tests:
526 if not self._is_storage_format_compatible(
527 self.old_version.storage_tests,
528 self.new_version.storage_tests,
529 compatibility_report):
Gilles Peskineada828f2019-07-04 19:17:40 +0200530 compliance_return_code = 1
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200531
Darryl Greenf2688e22019-05-29 11:29:08 +0100532 for version in [self.old_version, self.new_version]:
533 for mbed_module, mbed_module_dump in version.abi_dumps.items():
534 os.remove(mbed_module_dump)
Darryl Green3d3d5522019-02-25 17:01:55 +0000535 if self.can_remove_report_dir:
Darryl Green7c2dd582018-03-01 14:53:49 +0000536 os.rmdir(self.report_dir)
Gilles Peskineada828f2019-07-04 19:17:40 +0200537 self.log.info("\n".join(compatibility_report))
Darryl Green7c2dd582018-03-01 14:53:49 +0000538 return compliance_return_code
539
540 def check_for_abi_changes(self):
Gilles Peskine712afa72019-02-25 20:36:52 +0100541 """Generate a report of ABI differences
542 between self.old_rev and self.new_rev."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000543 self.check_repo_path()
Gilles Peskinef548a0c2022-03-03 10:22:36 +0100544 if self.check_api or self.check_abi:
545 self.check_abi_tools_are_installed()
Darryl Green3a5f6c82019-03-05 16:30:39 +0000546 self._get_abi_dump_for_ref(self.old_version)
547 self._get_abi_dump_for_ref(self.new_version)
Darryl Green7c2dd582018-03-01 14:53:49 +0000548 return self.get_abi_compatibility_report()
549
550
551def run_main():
552 try:
553 parser = argparse.ArgumentParser(
Gilles Peskine56354592022-03-03 10:23:09 +0100554 description=__doc__
Darryl Green7c2dd582018-03-01 14:53:49 +0000555 )
556 parser.add_argument(
Darryl Green3c3da792019-03-08 11:30:04 +0000557 "-v", "--verbose", action="store_true",
558 help="set verbosity level",
559 )
560 parser.add_argument(
Darryl Green418527b2018-04-16 12:02:29 +0100561 "-r", "--report-dir", type=str, default="reports",
Darryl Green7c2dd582018-03-01 14:53:49 +0000562 help="directory where reports are stored, default is reports",
563 )
564 parser.add_argument(
Darryl Green418527b2018-04-16 12:02:29 +0100565 "-k", "--keep-all-reports", action="store_true",
Darryl Green7c2dd582018-03-01 14:53:49 +0000566 help="keep all reports, even if there are no compatibility issues",
567 )
568 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000569 "-o", "--old-rev", type=str, help="revision for old version.",
570 required=True,
Darryl Green7c2dd582018-03-01 14:53:49 +0000571 )
572 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000573 "-or", "--old-repo", type=str, help="repository for old version."
Darryl Green9f357d62019-02-25 11:35:05 +0000574 )
575 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000576 "-oc", "--old-crypto-rev", type=str,
577 help="revision for old crypto submodule."
Darryl Green7c2dd582018-03-01 14:53:49 +0000578 )
Darryl Greenc2883a22019-02-20 15:01:56 +0000579 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000580 "-ocr", "--old-crypto-repo", type=str,
581 help="repository for old crypto submodule."
582 )
583 parser.add_argument(
584 "-n", "--new-rev", type=str, help="revision for new version",
585 required=True,
586 )
587 parser.add_argument(
588 "-nr", "--new-repo", type=str, help="repository for new version."
589 )
590 parser.add_argument(
591 "-nc", "--new-crypto-rev", type=str,
592 help="revision for new crypto version"
593 )
594 parser.add_argument(
595 "-ncr", "--new-crypto-repo", type=str,
596 help="repository for new crypto submodule."
Darryl Green9f357d62019-02-25 11:35:05 +0000597 )
598 parser.add_argument(
Darryl Greenc2883a22019-02-20 15:01:56 +0000599 "-s", "--skip-file", type=str,
Gilles Peskineb6ce2342019-07-04 19:00:31 +0200600 help=("path to file containing symbols and types to skip "
601 "(typically \"-s identifiers\" after running "
602 "\"tests/scripts/list-identifiers.sh --internal\")")
Darryl Greenc2883a22019-02-20 15:01:56 +0000603 )
Darryl Greene62f9bb2019-02-21 13:09:26 +0000604 parser.add_argument(
Gilles Peskine793778f2021-04-23 16:32:32 +0200605 "--check-abi",
606 action='store_true', default=True,
607 help="Perform ABI comparison (default: yes)"
608 )
609 parser.add_argument("--no-check-abi", action='store_false', dest='check_abi')
610 parser.add_argument(
611 "--check-api",
612 action='store_true', default=True,
613 help="Perform API comparison (default: yes)"
614 )
615 parser.add_argument("--no-check-api", action='store_false', dest='check_api')
616 parser.add_argument(
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200617 "--check-storage",
618 action='store_true', default=True,
619 help="Perform storage tests comparison (default: yes)"
620 )
621 parser.add_argument("--no-check-storage", action='store_false', dest='check_storage')
622 parser.add_argument(
Darryl Greene62f9bb2019-02-21 13:09:26 +0000623 "-b", "--brief", action="store_true",
624 help="output only the list of issues to stdout, instead of a full report",
625 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000626 abi_args = parser.parse_args()
Darryl Green492bc402019-04-11 15:50:41 +0100627 if os.path.isfile(abi_args.report_dir):
628 print("Error: {} is not a directory".format(abi_args.report_dir))
629 parser.exit()
Darryl Green0d1ca512019-04-09 09:14:17 +0100630 old_version = SimpleNamespace(
631 version="old",
632 repository=abi_args.old_repo,
633 revision=abi_args.old_rev,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200634 commit=None,
Darryl Green0d1ca512019-04-09 09:14:17 +0100635 crypto_repository=abi_args.old_crypto_repo,
636 crypto_revision=abi_args.old_crypto_rev,
637 abi_dumps={},
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200638 storage_tests={},
Darryl Green0d1ca512019-04-09 09:14:17 +0100639 modules={}
Darryl Green8184df52019-04-05 17:06:17 +0100640 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100641 new_version = SimpleNamespace(
642 version="new",
643 repository=abi_args.new_repo,
644 revision=abi_args.new_rev,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200645 commit=None,
Darryl Green0d1ca512019-04-09 09:14:17 +0100646 crypto_repository=abi_args.new_crypto_repo,
647 crypto_revision=abi_args.new_crypto_rev,
648 abi_dumps={},
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200649 storage_tests={},
Darryl Green0d1ca512019-04-09 09:14:17 +0100650 modules={}
Darryl Green8184df52019-04-05 17:06:17 +0100651 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100652 configuration = SimpleNamespace(
653 verbose=abi_args.verbose,
654 report_dir=abi_args.report_dir,
655 keep_all_reports=abi_args.keep_all_reports,
656 brief=abi_args.brief,
Gilles Peskine793778f2021-04-23 16:32:32 +0200657 check_abi=abi_args.check_abi,
658 check_api=abi_args.check_api,
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200659 check_storage=abi_args.check_storage,
Darryl Green0d1ca512019-04-09 09:14:17 +0100660 skip_file=abi_args.skip_file
Darryl Green7c2dd582018-03-01 14:53:49 +0000661 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100662 abi_check = AbiChecker(old_version, new_version, configuration)
Darryl Green7c2dd582018-03-01 14:53:49 +0000663 return_code = abi_check.check_for_abi_changes()
664 sys.exit(return_code)
Gilles Peskinee915d532019-02-25 21:39:42 +0100665 except Exception: # pylint: disable=broad-except
666 # Print the backtrace and exit explicitly so as to exit with
667 # status 2, not 1.
Darryl Greena6f430f2018-03-15 10:12:06 +0000668 traceback.print_exc()
Darryl Green7c2dd582018-03-01 14:53:49 +0000669 sys.exit(2)
670
671
672if __name__ == "__main__":
673 run_main()