blob: 7882681f1283d31e4afb4c1acb8b5df6687a17ab [file] [log] [blame]
Darryl Green7c2dd582018-03-01 14:53:49 +00001#!/usr/bin/env python3
Gilles Peskine6100d3c2022-06-20 18:51:18 +02002"""This script compares the interfaces of two versions of Mbed TLS, looking
Gilles Peskine92165362021-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 Peskine228d99b2022-06-20 18:51:44 +02006### How the script works ###
7
Gilles Peskine92165362021-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 Peskineca586a52022-02-22 19:02:44 +010013storage tests and the manual read tests, and complains if there is a
Gilles Peskine4a9630a2022-03-04 19:59:55 +010014reduction in coverage. A change in test data will be signaled as a
Gilles Peskineca586a52022-02-22 19:02:44 +010015coverage reduction since the old test data is no longer present. A change in
Gilles Peskine4a9630a2022-03-04 19:59:55 +010016how test data is presented will be signaled as well; this would be a false
Gilles Peskineca586a52022-02-22 19:02:44 +010017positive.
Gilles Peskine92165362021-04-23 16:37:12 +020018
Gilles Peskineca586a52022-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 Peskine92165362021-04-23 16:37:12 +020022while running the script.
Gilles Peskine644b3f62022-03-03 10:23:09 +010023
Gilles Peskine228d99b2022-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
Dave Rodgman16799db2023-11-02 19:47:20 +000087# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Bence Szépkútic7da1fe2020-05-26 01:54:15 +020088
Gilles Peskineca586a52022-02-22 19:02:44 +010089import glob
Darryl Green7c2dd582018-03-01 14:53:49 +000090import os
Gilles Peskine92165362021-04-23 16:37:12 +020091import re
Darryl Green7c2dd582018-03-01 14:53:49 +000092import sys
93import traceback
94import shutil
95import subprocess
96import argparse
97import logging
98import tempfile
Darryl Green9f357d62019-02-25 11:35:05 +000099import fnmatch
Darryl Green0d1ca512019-04-09 09:14:17 +0100100from types import SimpleNamespace
Darryl Green7c2dd582018-03-01 14:53:49 +0000101
Darryl Greene62f9bb2019-02-21 13:09:26 +0000102import xml.etree.ElementTree as ET
103
David Horstmann7f6c81a2024-05-10 16:58:31 +0100104import framework_scripts_path # pylint: disable=unused-import
David Horstmann9638ca32024-05-03 14:36:12 +0100105from mbedtls_framework import build_tree
Gilles Peskined9071e72022-09-18 21:17:09 +0200106
Darryl Green7c2dd582018-03-01 14:53:49 +0000107
Gilles Peskine184c0962020-03-24 18:25:17 +0100108class AbiChecker:
Gilles Peskine712afa72019-02-25 20:36:52 +0100109 """API and ABI checker."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000110
Darryl Green0d1ca512019-04-09 09:14:17 +0100111 def __init__(self, old_version, new_version, configuration):
Gilles Peskine712afa72019-02-25 20:36:52 +0100112 """Instantiate the API/ABI checker.
113
Darryl Green7c1a7332019-03-05 16:25:38 +0000114 old_version: RepoVersion containing details to compare against
115 new_version: RepoVersion containing details to check
Darryl Greenf67e3492019-04-12 15:17:02 +0100116 configuration.report_dir: directory for output files
117 configuration.keep_all_reports: if false, delete old reports
118 configuration.brief: if true, output shorter report to stdout
Gilles Peskine4a9630a2022-03-04 19:59:55 +0100119 configuration.check_abi: if true, compare ABIs
Gilles Peskinec76ab852021-04-23 16:32:32 +0200120 configuration.check_api: if true, compare APIs
Gilles Peskine92165362021-04-23 16:37:12 +0200121 configuration.check_storage: if true, compare storage format tests
Darryl Greenf67e3492019-04-12 15:17:02 +0100122 configuration.skip_file: path to file containing symbols and types to skip
Gilles Peskine712afa72019-02-25 20:36:52 +0100123 """
Darryl Green7c2dd582018-03-01 14:53:49 +0000124 self.repo_path = "."
125 self.log = None
Darryl Green0d1ca512019-04-09 09:14:17 +0100126 self.verbose = configuration.verbose
Darryl Green3a5f6c82019-03-05 16:30:39 +0000127 self._setup_logger()
Darryl Green0d1ca512019-04-09 09:14:17 +0100128 self.report_dir = os.path.abspath(configuration.report_dir)
129 self.keep_all_reports = configuration.keep_all_reports
Darryl Green492bc402019-04-11 15:50:41 +0100130 self.can_remove_report_dir = not (os.path.exists(self.report_dir) or
Darryl Green0d1ca512019-04-09 09:14:17 +0100131 self.keep_all_reports)
Darryl Green7c1a7332019-03-05 16:25:38 +0000132 self.old_version = old_version
133 self.new_version = new_version
Darryl Green0d1ca512019-04-09 09:14:17 +0100134 self.skip_file = configuration.skip_file
Gilles Peskinec76ab852021-04-23 16:32:32 +0200135 self.check_abi = configuration.check_abi
136 self.check_api = configuration.check_api
137 if self.check_abi != self.check_api:
138 raise Exception('Checking API without ABI or vice versa is not supported')
Gilles Peskine92165362021-04-23 16:37:12 +0200139 self.check_storage_tests = configuration.check_storage
Darryl Green0d1ca512019-04-09 09:14:17 +0100140 self.brief = configuration.brief
Darryl Green7c2dd582018-03-01 14:53:49 +0000141 self.git_command = "git"
142 self.make_command = "make"
143
Darryl Green3a5f6c82019-03-05 16:30:39 +0000144 def _setup_logger(self):
Darryl Green7c2dd582018-03-01 14:53:49 +0000145 self.log = logging.getLogger()
Darryl Green3c3da792019-03-08 11:30:04 +0000146 if self.verbose:
147 self.log.setLevel(logging.DEBUG)
148 else:
149 self.log.setLevel(logging.INFO)
Darryl Green7c2dd582018-03-01 14:53:49 +0000150 self.log.addHandler(logging.StreamHandler())
151
Gilles Peskine712afa72019-02-25 20:36:52 +0100152 @staticmethod
153 def check_abi_tools_are_installed():
Darryl Green7c2dd582018-03-01 14:53:49 +0000154 for command in ["abi-dumper", "abi-compliance-checker"]:
155 if not shutil.which(command):
156 raise Exception("{} not installed, aborting".format(command))
157
Darryl Green3a5f6c82019-03-05 16:30:39 +0000158 def _get_clean_worktree_for_git_revision(self, version):
Darryl Green7c1a7332019-03-05 16:25:38 +0000159 """Make a separate worktree with version.revision checked out.
Gilles Peskine712afa72019-02-25 20:36:52 +0100160 Do not modify the current worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000161 git_worktree_path = tempfile.mkdtemp()
Darryl Green7c1a7332019-03-05 16:25:38 +0000162 if version.repository:
Darryl Green3c3da792019-03-08 11:30:04 +0000163 self.log.debug(
Darryl Greenda84e322019-02-19 16:59:33 +0000164 "Checking out git worktree for revision {} from {}".format(
Darryl Green7c1a7332019-03-05 16:25:38 +0000165 version.revision, version.repository
Darryl Greenda84e322019-02-19 16:59:33 +0000166 )
167 )
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100168 fetch_output = subprocess.check_output(
Darryl Green7c1a7332019-03-05 16:25:38 +0000169 [self.git_command, "fetch",
170 version.repository, version.revision],
Darryl Greenda84e322019-02-19 16:59:33 +0000171 cwd=self.repo_path,
Darryl Greenda84e322019-02-19 16:59:33 +0000172 stderr=subprocess.STDOUT
173 )
Darryl Green3c3da792019-03-08 11:30:04 +0000174 self.log.debug(fetch_output.decode("utf-8"))
Darryl Greenda84e322019-02-19 16:59:33 +0000175 worktree_rev = "FETCH_HEAD"
176 else:
Darryl Green3c3da792019-03-08 11:30:04 +0000177 self.log.debug("Checking out git worktree for revision {}".format(
Darryl Green7c1a7332019-03-05 16:25:38 +0000178 version.revision
179 ))
180 worktree_rev = version.revision
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100181 worktree_output = subprocess.check_output(
Darryl Greenda84e322019-02-19 16:59:33 +0000182 [self.git_command, "worktree", "add", "--detach",
183 git_worktree_path, worktree_rev],
Darryl Green7c2dd582018-03-01 14:53:49 +0000184 cwd=self.repo_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000185 stderr=subprocess.STDOUT
186 )
Darryl Green3c3da792019-03-08 11:30:04 +0000187 self.log.debug(worktree_output.decode("utf-8"))
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200188 version.commit = subprocess.check_output(
Darryl Green762351b2019-07-25 14:33:33 +0100189 [self.git_command, "rev-parse", "HEAD"],
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200190 cwd=git_worktree_path,
191 stderr=subprocess.STDOUT
192 ).decode("ascii").rstrip()
193 self.log.debug("Commit is {}".format(version.commit))
Darryl Green7c2dd582018-03-01 14:53:49 +0000194 return git_worktree_path
195
Darryl Green3a5f6c82019-03-05 16:30:39 +0000196 def _update_git_submodules(self, git_worktree_path, version):
Darryl Green8184df52019-04-05 17:06:17 +0100197 """If the crypto submodule is present, initialize it.
198 if version.crypto_revision exists, update it to that revision,
199 otherwise update it to the default revision"""
Bence Szépkúticdd16622025-09-25 15:51:07 +0200200 submodule_output = subprocess.check_output(
201 [self.git_command, "submodule", "foreach", "--recursive",
Bence Szépkúti99fa0ab2025-09-26 15:37:42 +0200202 f'git worktree add --detach "{git_worktree_path}/$displaypath" HEAD'],
Bence Szépkúticdd16622025-09-25 15:51:07 +0200203 cwd=self.repo_path,
204 stderr=subprocess.STDOUT
205 )
206 self.log.debug(submodule_output.decode("utf-8"))
Bence Szépkútie45e5042025-09-26 20:10:04 +0200207
208 try:
209 # Try to update the submodules using local commits
Bence Szépkúti616f9fd2025-09-29 14:24:25 +0200210 # (Git will sometimes insist on fetching the remote without --no-fetch
211 # if the submodules are shallow clones)
Bence Szépkútie45e5042025-09-26 20:10:04 +0200212 update_output = subprocess.check_output(
213 [self.git_command, "submodule", "update", "--init", '--recursive', '--no-fetch'],
214 cwd=git_worktree_path,
215 stderr=subprocess.STDOUT
216 )
217 except subprocess.CalledProcessError as err:
218 self.log.debug(err.stdout.decode("utf-8"))
219
220 # Checkout with --no-fetch failed, falling back to fetching from origin
221 update_output = subprocess.check_output(
222 [self.git_command, "submodule", "update", "--init", '--recursive'],
223 cwd=git_worktree_path,
224 stderr=subprocess.STDOUT
225 )
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100226 self.log.debug(update_output.decode("utf-8"))
Darryl Greene29ce702019-03-05 15:23:25 +0000227 if not (os.path.exists(os.path.join(git_worktree_path, "crypto"))
Darryl Green7c1a7332019-03-05 16:25:38 +0000228 and version.crypto_revision):
Darryl Greene29ce702019-03-05 15:23:25 +0000229 return
230
Darryl Green7c1a7332019-03-05 16:25:38 +0000231 if version.crypto_repository:
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100232 fetch_output = subprocess.check_output(
Darryl Green1d95c532019-03-08 11:12:19 +0000233 [self.git_command, "fetch", version.crypto_repository,
234 version.crypto_revision],
Darryl Greene29ce702019-03-05 15:23:25 +0000235 cwd=os.path.join(git_worktree_path, "crypto"),
Darryl Greene29ce702019-03-05 15:23:25 +0000236 stderr=subprocess.STDOUT
237 )
Darryl Green3c3da792019-03-08 11:30:04 +0000238 self.log.debug(fetch_output.decode("utf-8"))
Darryl Green1d95c532019-03-08 11:12:19 +0000239 crypto_rev = "FETCH_HEAD"
240 else:
241 crypto_rev = version.crypto_revision
242
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100243 checkout_output = subprocess.check_output(
Darryl Green1d95c532019-03-08 11:12:19 +0000244 [self.git_command, "checkout", crypto_rev],
245 cwd=os.path.join(git_worktree_path, "crypto"),
Darryl Green1d95c532019-03-08 11:12:19 +0000246 stderr=subprocess.STDOUT
247 )
Darryl Green3c3da792019-03-08 11:30:04 +0000248 self.log.debug(checkout_output.decode("utf-8"))
Jaeden Ameroffeb1b82018-11-02 16:35:09 +0000249
Darryl Green3a5f6c82019-03-05 16:30:39 +0000250 def _build_shared_libraries(self, git_worktree_path, version):
Gilles Peskine712afa72019-02-25 20:36:52 +0100251 """Build the shared libraries in the specified worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000252 my_environment = os.environ.copy()
253 my_environment["CFLAGS"] = "-g -Og"
254 my_environment["SHARED"] = "1"
Darryl Greend2dba362019-05-09 13:03:05 +0100255 if os.path.exists(os.path.join(git_worktree_path, "crypto")):
256 my_environment["USE_CRYPTO_SUBMODULE"] = "1"
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100257 make_output = subprocess.check_output(
Darryl Greenddf25a62019-02-28 11:52:39 +0000258 [self.make_command, "lib"],
Darryl Green7c2dd582018-03-01 14:53:49 +0000259 env=my_environment,
260 cwd=git_worktree_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000261 stderr=subprocess.STDOUT
262 )
Darryl Green3c3da792019-03-08 11:30:04 +0000263 self.log.debug(make_output.decode("utf-8"))
Darryl Greenf025d532019-04-12 15:18:02 +0100264 for root, _dirs, files in os.walk(git_worktree_path):
Darryl Green9f357d62019-02-25 11:35:05 +0000265 for file in fnmatch.filter(files, "*.so"):
Darryl Green7c1a7332019-03-05 16:25:38 +0000266 version.modules[os.path.splitext(file)[0]] = (
Darryl Green3e7a9802019-02-27 16:53:40 +0000267 os.path.join(root, file)
Darryl Green9f357d62019-02-25 11:35:05 +0000268 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000269
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200270 @staticmethod
271 def _pretty_revision(version):
272 if version.revision == version.commit:
273 return version.revision
274 else:
275 return "{} ({})".format(version.revision, version.commit)
276
Darryl Green8184df52019-04-05 17:06:17 +0100277 def _get_abi_dumps_from_shared_libraries(self, version):
Gilles Peskine712afa72019-02-25 20:36:52 +0100278 """Generate the ABI dumps for the specified git revision.
Darryl Green8184df52019-04-05 17:06:17 +0100279 The shared libraries must have been built and the module paths
280 present in version.modules."""
Darryl Green7c1a7332019-03-05 16:25:38 +0000281 for mbed_module, module_path in version.modules.items():
Darryl Green7c2dd582018-03-01 14:53:49 +0000282 output_path = os.path.join(
Darryl Greenfe9a6752019-04-04 14:39:33 +0100283 self.report_dir, "{}-{}-{}.dump".format(
284 mbed_module, version.revision, version.version
Darryl Green3e7a9802019-02-27 16:53:40 +0000285 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000286 )
287 abi_dump_command = [
288 "abi-dumper",
Darryl Green9f357d62019-02-25 11:35:05 +0000289 module_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000290 "-o", output_path,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200291 "-lver", self._pretty_revision(version),
Darryl Green7c2dd582018-03-01 14:53:49 +0000292 ]
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100293 abi_dump_output = subprocess.check_output(
Darryl Green7c2dd582018-03-01 14:53:49 +0000294 abi_dump_command,
Darryl Green7c2dd582018-03-01 14:53:49 +0000295 stderr=subprocess.STDOUT
296 )
Darryl Green3c3da792019-03-08 11:30:04 +0000297 self.log.debug(abi_dump_output.decode("utf-8"))
Darryl Green7c1a7332019-03-05 16:25:38 +0000298 version.abi_dumps[mbed_module] = output_path
Darryl Green7c2dd582018-03-01 14:53:49 +0000299
Gilles Peskine92165362021-04-23 16:37:12 +0200300 @staticmethod
301 def _normalize_storage_test_case_data(line):
302 """Eliminate cosmetic or irrelevant details in storage format test cases."""
303 line = re.sub(r'\s+', r'', line)
304 return line
305
Gilles Peskineca586a52022-02-22 19:02:44 +0100306 def _read_storage_tests(self,
307 directory,
308 filename,
309 is_generated,
310 storage_tests):
Gilles Peskine92165362021-04-23 16:37:12 +0200311 """Record storage tests from the given file.
312
313 Populate the storage_tests dictionary with test cases read from
314 filename under directory.
315 """
316 at_paragraph_start = True
317 description = None
318 full_path = os.path.join(directory, filename)
Gilles Peskinedcf2ff52022-03-04 20:02:00 +0100319 with open(full_path) as fd:
320 for line_number, line in enumerate(fd, 1):
321 line = line.strip()
322 if not line:
323 at_paragraph_start = True
Gilles Peskineca586a52022-02-22 19:02:44 +0100324 continue
Gilles Peskinedcf2ff52022-03-04 20:02:00 +0100325 if line.startswith('#'):
326 continue
327 if at_paragraph_start:
328 description = line.strip()
329 at_paragraph_start = False
330 continue
331 if line.startswith('depends_on:'):
332 continue
333 # We've reached a test case data line
334 test_case_data = self._normalize_storage_test_case_data(line)
335 if not is_generated:
336 # In manual test data, only look at read tests.
337 function_name = test_case_data.split(':', 1)[0]
338 if 'read' not in function_name.split('_'):
339 continue
340 metadata = SimpleNamespace(
341 filename=filename,
342 line_number=line_number,
343 description=description
344 )
345 storage_tests[test_case_data] = metadata
Gilles Peskine92165362021-04-23 16:37:12 +0200346
Gilles Peskineca586a52022-02-22 19:02:44 +0100347 @staticmethod
348 def _list_generated_test_data_files(git_worktree_path):
349 """List the generated test data files."""
David Horstmann8d398ee2024-05-31 14:38:52 +0100350 generate_psa_tests = 'framework/scripts/generate_psa_tests.py'
351 if not os.path.isfile(git_worktree_path + '/' + generate_psa_tests):
352 # The checked-out revision is from before generate_psa_tests.py
353 # was moved to the framework submodule. Use the old location.
354 generate_psa_tests = 'tests/scripts/generate_psa_tests.py'
355
Gilles Peskineca586a52022-02-22 19:02:44 +0100356 output = subprocess.check_output(
David Horstmann8d398ee2024-05-31 14:38:52 +0100357 [generate_psa_tests, '--list'],
Gilles Peskine92165362021-04-23 16:37:12 +0200358 cwd=git_worktree_path,
359 ).decode('ascii')
Gilles Peskineca586a52022-02-22 19:02:44 +0100360 return [line for line in output.split('\n') if line]
361
362 def _get_storage_format_tests(self, version, git_worktree_path):
363 """Record the storage format tests for the specified git version.
364
365 The storage format tests are the test suite data files whose name
366 contains "storage_format".
367
368 The version must be checked out at git_worktree_path.
369
370 This function creates or updates the generated data files.
371 """
372 # Existing test data files. This may be missing some automatically
373 # generated files if they haven't been generated yet.
374 storage_data_files = set(glob.glob(
375 'tests/suites/test_suite_*storage_format*.data'
376 ))
377 # Discover and (re)generate automatically generated data files.
378 to_be_generated = set()
379 for filename in self._list_generated_test_data_files(git_worktree_path):
380 if 'storage_format' in filename:
381 storage_data_files.add(filename)
382 to_be_generated.add(filename)
David Horstmann8d398ee2024-05-31 14:38:52 +0100383
384 generate_psa_tests = 'framework/scripts/generate_psa_tests.py'
385 if not os.path.isfile(git_worktree_path + '/' + generate_psa_tests):
386 # The checked-out revision is from before generate_psa_tests.py
387 # was moved to the framework submodule. Use the old location.
388 generate_psa_tests = 'tests/scripts/generate_psa_tests.py'
Gilles Peskine92165362021-04-23 16:37:12 +0200389 subprocess.check_call(
David Horstmann8d398ee2024-05-31 14:38:52 +0100390 [generate_psa_tests] + sorted(to_be_generated),
Gilles Peskine92165362021-04-23 16:37:12 +0200391 cwd=git_worktree_path,
392 )
Gilles Peskineca586a52022-02-22 19:02:44 +0100393 for test_file in sorted(storage_data_files):
394 self._read_storage_tests(git_worktree_path,
395 test_file,
396 test_file in to_be_generated,
Gilles Peskine92165362021-04-23 16:37:12 +0200397 version.storage_tests)
398
Darryl Green3a5f6c82019-03-05 16:30:39 +0000399 def _cleanup_worktree(self, git_worktree_path):
Gilles Peskine712afa72019-02-25 20:36:52 +0100400 """Remove the specified git worktree."""
Darryl Green7c2dd582018-03-01 14:53:49 +0000401 shutil.rmtree(git_worktree_path)
Bence Szépkúticdd16622025-09-25 15:51:07 +0200402 submodule_output = subprocess.check_output(
Bence Szépkútid0404272025-09-26 15:44:11 +0200403 [self.git_command, "submodule", "foreach", "--recursive",
404 f'git worktree remove "{git_worktree_path}/$displaypath"'],
Bence Szépkúticdd16622025-09-25 15:51:07 +0200405 cwd=self.repo_path,
406 stderr=subprocess.STDOUT
407 )
408 self.log.debug(submodule_output.decode("utf-8"))
Darryl Greenb2ee0b82019-04-12 16:24:25 +0100409 worktree_output = subprocess.check_output(
Bence Szépkútid0404272025-09-26 15:44:11 +0200410 [self.git_command, "worktree", "remove", git_worktree_path],
Darryl Green7c2dd582018-03-01 14:53:49 +0000411 cwd=self.repo_path,
Darryl Green7c2dd582018-03-01 14:53:49 +0000412 stderr=subprocess.STDOUT
413 )
Darryl Green3c3da792019-03-08 11:30:04 +0000414 self.log.debug(worktree_output.decode("utf-8"))
Darryl Green7c2dd582018-03-01 14:53:49 +0000415
Darryl Green3a5f6c82019-03-05 16:30:39 +0000416 def _get_abi_dump_for_ref(self, version):
Gilles Peskine92165362021-04-23 16:37:12 +0200417 """Generate the interface information for the specified git revision."""
Darryl Green3a5f6c82019-03-05 16:30:39 +0000418 git_worktree_path = self._get_clean_worktree_for_git_revision(version)
419 self._update_git_submodules(git_worktree_path, version)
Gilles Peskinec76ab852021-04-23 16:32:32 +0200420 if self.check_abi:
421 self._build_shared_libraries(git_worktree_path, version)
422 self._get_abi_dumps_from_shared_libraries(version)
Gilles Peskine92165362021-04-23 16:37:12 +0200423 if self.check_storage_tests:
424 self._get_storage_format_tests(version, git_worktree_path)
Darryl Green3a5f6c82019-03-05 16:30:39 +0000425 self._cleanup_worktree(git_worktree_path)
Darryl Green7c2dd582018-03-01 14:53:49 +0000426
Darryl Green3a5f6c82019-03-05 16:30:39 +0000427 def _remove_children_with_tag(self, parent, tag):
Darryl Greene62f9bb2019-02-21 13:09:26 +0000428 children = parent.getchildren()
429 for child in children:
430 if child.tag == tag:
431 parent.remove(child)
432 else:
Darryl Green3a5f6c82019-03-05 16:30:39 +0000433 self._remove_children_with_tag(child, tag)
Darryl Greene62f9bb2019-02-21 13:09:26 +0000434
Darryl Green3a5f6c82019-03-05 16:30:39 +0000435 def _remove_extra_detail_from_report(self, report_root):
Darryl Greene62f9bb2019-02-21 13:09:26 +0000436 for tag in ['test_info', 'test_results', 'problem_summary',
Darryl Greenc6f874b2019-06-05 12:57:50 +0100437 'added_symbols', 'affected']:
Darryl Green3a5f6c82019-03-05 16:30:39 +0000438 self._remove_children_with_tag(report_root, tag)
Darryl Greene62f9bb2019-02-21 13:09:26 +0000439
440 for report in report_root:
441 for problems in report.getchildren()[:]:
442 if not problems.getchildren():
443 report.remove(problems)
444
Gilles Peskineada828f2019-07-04 19:17:40 +0200445 def _abi_compliance_command(self, mbed_module, output_path):
446 """Build the command to run to analyze the library mbed_module.
447 The report will be placed in output_path."""
448 abi_compliance_command = [
449 "abi-compliance-checker",
450 "-l", mbed_module,
451 "-old", self.old_version.abi_dumps[mbed_module],
452 "-new", self.new_version.abi_dumps[mbed_module],
453 "-strict",
454 "-report-path", output_path,
455 ]
456 if self.skip_file:
457 abi_compliance_command += ["-skip-symbols", self.skip_file,
458 "-skip-types", self.skip_file]
459 if self.brief:
460 abi_compliance_command += ["-report-format", "xml",
461 "-stdout"]
462 return abi_compliance_command
463
464 def _is_library_compatible(self, mbed_module, compatibility_report):
465 """Test if the library mbed_module has remained compatible.
466 Append a message regarding compatibility to compatibility_report."""
467 output_path = os.path.join(
468 self.report_dir, "{}-{}-{}.html".format(
469 mbed_module, self.old_version.revision,
470 self.new_version.revision
471 )
472 )
473 try:
474 subprocess.check_output(
475 self._abi_compliance_command(mbed_module, output_path),
476 stderr=subprocess.STDOUT
477 )
478 except subprocess.CalledProcessError as err:
479 if err.returncode != 1:
480 raise err
481 if self.brief:
482 self.log.info(
483 "Compatibility issues found for {}".format(mbed_module)
484 )
485 report_root = ET.fromstring(err.output.decode("utf-8"))
486 self._remove_extra_detail_from_report(report_root)
487 self.log.info(ET.tostring(report_root).decode("utf-8"))
488 else:
489 self.can_remove_report_dir = False
490 compatibility_report.append(
491 "Compatibility issues found for {}, "
492 "for details see {}".format(mbed_module, output_path)
493 )
494 return False
495 compatibility_report.append(
496 "No compatibility issues for {}".format(mbed_module)
497 )
498 if not (self.keep_all_reports or self.brief):
499 os.remove(output_path)
500 return True
501
Gilles Peskine92165362021-04-23 16:37:12 +0200502 @staticmethod
503 def _is_storage_format_compatible(old_tests, new_tests,
504 compatibility_report):
505 """Check whether all tests present in old_tests are also in new_tests.
506
507 Append a message regarding compatibility to compatibility_report.
508 """
509 missing = frozenset(old_tests.keys()).difference(new_tests.keys())
510 for test_data in sorted(missing):
511 metadata = old_tests[test_data]
512 compatibility_report.append(
513 'Test case from {} line {} "{}" has disappeared: {}'.format(
514 metadata.filename, metadata.line_number,
515 metadata.description, test_data
516 )
517 )
518 compatibility_report.append(
519 'FAIL: {}/{} storage format test cases have changed or disappeared.'.format(
520 len(missing), len(old_tests)
521 ) if missing else
522 'PASS: All {} storage format test cases are preserved.'.format(
523 len(old_tests)
524 )
525 )
526 compatibility_report.append(
527 'Info: number of storage format tests cases: {} -> {}.'.format(
528 len(old_tests), len(new_tests)
529 )
530 )
531 return not missing
532
Darryl Green7c2dd582018-03-01 14:53:49 +0000533 def get_abi_compatibility_report(self):
Gilles Peskine712afa72019-02-25 20:36:52 +0100534 """Generate a report of the differences between the reference ABI
Darryl Green8184df52019-04-05 17:06:17 +0100535 and the new ABI. ABI dumps from self.old_version and self.new_version
536 must be available."""
Gilles Peskineada828f2019-07-04 19:17:40 +0200537 compatibility_report = ["Checking evolution from {} to {}".format(
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200538 self._pretty_revision(self.old_version),
539 self._pretty_revision(self.new_version)
Gilles Peskineada828f2019-07-04 19:17:40 +0200540 )]
Darryl Green7c2dd582018-03-01 14:53:49 +0000541 compliance_return_code = 0
Gilles Peskine92165362021-04-23 16:37:12 +0200542
Gilles Peskinec76ab852021-04-23 16:32:32 +0200543 if self.check_abi:
544 shared_modules = list(set(self.old_version.modules.keys()) &
545 set(self.new_version.modules.keys()))
546 for mbed_module in shared_modules:
547 if not self._is_library_compatible(mbed_module,
548 compatibility_report):
549 compliance_return_code = 1
550
Gilles Peskine92165362021-04-23 16:37:12 +0200551 if self.check_storage_tests:
552 if not self._is_storage_format_compatible(
553 self.old_version.storage_tests,
554 self.new_version.storage_tests,
555 compatibility_report):
Gilles Peskineada828f2019-07-04 19:17:40 +0200556 compliance_return_code = 1
Gilles Peskine92165362021-04-23 16:37:12 +0200557
Darryl Greenf2688e22019-05-29 11:29:08 +0100558 for version in [self.old_version, self.new_version]:
559 for mbed_module, mbed_module_dump in version.abi_dumps.items():
560 os.remove(mbed_module_dump)
Darryl Green3d3d5522019-02-25 17:01:55 +0000561 if self.can_remove_report_dir:
Darryl Green7c2dd582018-03-01 14:53:49 +0000562 os.rmdir(self.report_dir)
Gilles Peskineada828f2019-07-04 19:17:40 +0200563 self.log.info("\n".join(compatibility_report))
Darryl Green7c2dd582018-03-01 14:53:49 +0000564 return compliance_return_code
565
566 def check_for_abi_changes(self):
Gilles Peskine712afa72019-02-25 20:36:52 +0100567 """Generate a report of ABI differences
568 between self.old_rev and self.new_rev."""
Gilles Peskined9071e72022-09-18 21:17:09 +0200569 build_tree.check_repo_path()
Gilles Peskine93c2a422022-03-03 10:22:36 +0100570 if self.check_api or self.check_abi:
571 self.check_abi_tools_are_installed()
Darryl Green3a5f6c82019-03-05 16:30:39 +0000572 self._get_abi_dump_for_ref(self.old_version)
573 self._get_abi_dump_for_ref(self.new_version)
Darryl Green7c2dd582018-03-01 14:53:49 +0000574 return self.get_abi_compatibility_report()
575
576
577def run_main():
578 try:
579 parser = argparse.ArgumentParser(
Gilles Peskine644b3f62022-03-03 10:23:09 +0100580 description=__doc__
Darryl Green7c2dd582018-03-01 14:53:49 +0000581 )
582 parser.add_argument(
Darryl Green3c3da792019-03-08 11:30:04 +0000583 "-v", "--verbose", action="store_true",
584 help="set verbosity level",
585 )
586 parser.add_argument(
Darryl Green418527b2018-04-16 12:02:29 +0100587 "-r", "--report-dir", type=str, default="reports",
Darryl Green7c2dd582018-03-01 14:53:49 +0000588 help="directory where reports are stored, default is reports",
589 )
590 parser.add_argument(
Darryl Green418527b2018-04-16 12:02:29 +0100591 "-k", "--keep-all-reports", action="store_true",
Darryl Green7c2dd582018-03-01 14:53:49 +0000592 help="keep all reports, even if there are no compatibility issues",
593 )
594 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000595 "-o", "--old-rev", type=str, help="revision for old version.",
596 required=True,
Darryl Green7c2dd582018-03-01 14:53:49 +0000597 )
598 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000599 "-or", "--old-repo", type=str, help="repository for old version."
Darryl Green9f357d62019-02-25 11:35:05 +0000600 )
601 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000602 "-oc", "--old-crypto-rev", type=str,
603 help="revision for old crypto submodule."
Darryl Green7c2dd582018-03-01 14:53:49 +0000604 )
Darryl Greenc2883a22019-02-20 15:01:56 +0000605 parser.add_argument(
Darryl Greenc5132ff2019-03-01 09:54:44 +0000606 "-ocr", "--old-crypto-repo", type=str,
607 help="repository for old crypto submodule."
608 )
609 parser.add_argument(
610 "-n", "--new-rev", type=str, help="revision for new version",
611 required=True,
612 )
613 parser.add_argument(
614 "-nr", "--new-repo", type=str, help="repository for new version."
615 )
616 parser.add_argument(
617 "-nc", "--new-crypto-rev", type=str,
618 help="revision for new crypto version"
619 )
620 parser.add_argument(
621 "-ncr", "--new-crypto-repo", type=str,
622 help="repository for new crypto submodule."
Darryl Green9f357d62019-02-25 11:35:05 +0000623 )
624 parser.add_argument(
Darryl Greenc2883a22019-02-20 15:01:56 +0000625 "-s", "--skip-file", type=str,
Gilles Peskineb6ce2342019-07-04 19:00:31 +0200626 help=("path to file containing symbols and types to skip "
627 "(typically \"-s identifiers\" after running "
628 "\"tests/scripts/list-identifiers.sh --internal\")")
Darryl Greenc2883a22019-02-20 15:01:56 +0000629 )
Darryl Greene62f9bb2019-02-21 13:09:26 +0000630 parser.add_argument(
Gilles Peskinec76ab852021-04-23 16:32:32 +0200631 "--check-abi",
632 action='store_true', default=True,
633 help="Perform ABI comparison (default: yes)"
634 )
635 parser.add_argument("--no-check-abi", action='store_false', dest='check_abi')
636 parser.add_argument(
637 "--check-api",
638 action='store_true', default=True,
639 help="Perform API comparison (default: yes)"
640 )
641 parser.add_argument("--no-check-api", action='store_false', dest='check_api')
642 parser.add_argument(
Gilles Peskine92165362021-04-23 16:37:12 +0200643 "--check-storage",
644 action='store_true', default=True,
645 help="Perform storage tests comparison (default: yes)"
646 )
647 parser.add_argument("--no-check-storage", action='store_false', dest='check_storage')
648 parser.add_argument(
Darryl Greene62f9bb2019-02-21 13:09:26 +0000649 "-b", "--brief", action="store_true",
650 help="output only the list of issues to stdout, instead of a full report",
651 )
Darryl Green7c2dd582018-03-01 14:53:49 +0000652 abi_args = parser.parse_args()
Darryl Green492bc402019-04-11 15:50:41 +0100653 if os.path.isfile(abi_args.report_dir):
654 print("Error: {} is not a directory".format(abi_args.report_dir))
655 parser.exit()
Darryl Green0d1ca512019-04-09 09:14:17 +0100656 old_version = SimpleNamespace(
657 version="old",
658 repository=abi_args.old_repo,
659 revision=abi_args.old_rev,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200660 commit=None,
Darryl Green0d1ca512019-04-09 09:14:17 +0100661 crypto_repository=abi_args.old_crypto_repo,
662 crypto_revision=abi_args.old_crypto_rev,
663 abi_dumps={},
Gilles Peskine92165362021-04-23 16:37:12 +0200664 storage_tests={},
Darryl Green0d1ca512019-04-09 09:14:17 +0100665 modules={}
Darryl Green8184df52019-04-05 17:06:17 +0100666 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100667 new_version = SimpleNamespace(
668 version="new",
669 repository=abi_args.new_repo,
670 revision=abi_args.new_rev,
Gilles Peskine3e2da4a2019-07-04 19:01:22 +0200671 commit=None,
Darryl Green0d1ca512019-04-09 09:14:17 +0100672 crypto_repository=abi_args.new_crypto_repo,
673 crypto_revision=abi_args.new_crypto_rev,
674 abi_dumps={},
Gilles Peskine92165362021-04-23 16:37:12 +0200675 storage_tests={},
Darryl Green0d1ca512019-04-09 09:14:17 +0100676 modules={}
Darryl Green8184df52019-04-05 17:06:17 +0100677 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100678 configuration = SimpleNamespace(
679 verbose=abi_args.verbose,
680 report_dir=abi_args.report_dir,
681 keep_all_reports=abi_args.keep_all_reports,
682 brief=abi_args.brief,
Gilles Peskinec76ab852021-04-23 16:32:32 +0200683 check_abi=abi_args.check_abi,
684 check_api=abi_args.check_api,
Gilles Peskine92165362021-04-23 16:37:12 +0200685 check_storage=abi_args.check_storage,
Darryl Green0d1ca512019-04-09 09:14:17 +0100686 skip_file=abi_args.skip_file
Darryl Green7c2dd582018-03-01 14:53:49 +0000687 )
Darryl Green0d1ca512019-04-09 09:14:17 +0100688 abi_check = AbiChecker(old_version, new_version, configuration)
Darryl Green7c2dd582018-03-01 14:53:49 +0000689 return_code = abi_check.check_for_abi_changes()
690 sys.exit(return_code)
Gilles Peskinee915d532019-02-25 21:39:42 +0100691 except Exception: # pylint: disable=broad-except
692 # Print the backtrace and exit explicitly so as to exit with
693 # status 2, not 1.
Darryl Greena6f430f2018-03-15 10:12:06 +0000694 traceback.print_exc()
Darryl Green7c2dd582018-03-01 14:53:49 +0000695 sys.exit(2)
696
697
698if __name__ == "__main__":
699 run_main()