abi_check.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/env python3
  2. """
  3. Purpose
  4. This script is a small wrapper around the abi-compliance-checker and
  5. abi-dumper tools, applying them to compare the ABI and API of the library
  6. files from two different Git revisions within an Mbed TLS repository.
  7. The results of the comparison are either formatted as HTML and stored at
  8. a configurable location, or are given as a brief list of problems.
  9. Returns 0 on success, 1 on ABI/API non-compliance, and 2 if there is an error
  10. while running the script. Note: must be run from Mbed TLS root.
  11. """
  12. # Copyright The Mbed TLS Contributors
  13. # SPDX-License-Identifier: Apache-2.0
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  16. # not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  23. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. import os
  27. import sys
  28. import traceback
  29. import shutil
  30. import subprocess
  31. import argparse
  32. import logging
  33. import tempfile
  34. import fnmatch
  35. from types import SimpleNamespace
  36. import xml.etree.ElementTree as ET
  37. class AbiChecker:
  38. """API and ABI checker."""
  39. def __init__(self, old_version, new_version, configuration):
  40. """Instantiate the API/ABI checker.
  41. old_version: RepoVersion containing details to compare against
  42. new_version: RepoVersion containing details to check
  43. configuration.report_dir: directory for output files
  44. configuration.keep_all_reports: if false, delete old reports
  45. configuration.brief: if true, output shorter report to stdout
  46. configuration.skip_file: path to file containing symbols and types to skip
  47. """
  48. self.repo_path = "."
  49. self.log = None
  50. self.verbose = configuration.verbose
  51. self._setup_logger()
  52. self.report_dir = os.path.abspath(configuration.report_dir)
  53. self.keep_all_reports = configuration.keep_all_reports
  54. self.can_remove_report_dir = not (os.path.exists(self.report_dir) or
  55. self.keep_all_reports)
  56. self.old_version = old_version
  57. self.new_version = new_version
  58. self.skip_file = configuration.skip_file
  59. self.brief = configuration.brief
  60. self.git_command = "git"
  61. self.make_command = "make"
  62. @staticmethod
  63. def check_repo_path():
  64. if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
  65. raise Exception("Must be run from Mbed TLS root")
  66. def _setup_logger(self):
  67. self.log = logging.getLogger()
  68. if self.verbose:
  69. self.log.setLevel(logging.DEBUG)
  70. else:
  71. self.log.setLevel(logging.INFO)
  72. self.log.addHandler(logging.StreamHandler())
  73. @staticmethod
  74. def check_abi_tools_are_installed():
  75. for command in ["abi-dumper", "abi-compliance-checker"]:
  76. if not shutil.which(command):
  77. raise Exception("{} not installed, aborting".format(command))
  78. def _get_clean_worktree_for_git_revision(self, version):
  79. """Make a separate worktree with version.revision checked out.
  80. Do not modify the current worktree."""
  81. git_worktree_path = tempfile.mkdtemp()
  82. if version.repository:
  83. self.log.debug(
  84. "Checking out git worktree for revision {} from {}".format(
  85. version.revision, version.repository
  86. )
  87. )
  88. fetch_output = subprocess.check_output(
  89. [self.git_command, "fetch",
  90. version.repository, version.revision],
  91. cwd=self.repo_path,
  92. stderr=subprocess.STDOUT
  93. )
  94. self.log.debug(fetch_output.decode("utf-8"))
  95. worktree_rev = "FETCH_HEAD"
  96. else:
  97. self.log.debug("Checking out git worktree for revision {}".format(
  98. version.revision
  99. ))
  100. worktree_rev = version.revision
  101. worktree_output = subprocess.check_output(
  102. [self.git_command, "worktree", "add", "--detach",
  103. git_worktree_path, worktree_rev],
  104. cwd=self.repo_path,
  105. stderr=subprocess.STDOUT
  106. )
  107. self.log.debug(worktree_output.decode("utf-8"))
  108. version.commit = subprocess.check_output(
  109. [self.git_command, "rev-parse", "HEAD"],
  110. cwd=git_worktree_path,
  111. stderr=subprocess.STDOUT
  112. ).decode("ascii").rstrip()
  113. self.log.debug("Commit is {}".format(version.commit))
  114. return git_worktree_path
  115. def _update_git_submodules(self, git_worktree_path, version):
  116. """If the crypto submodule is present, initialize it.
  117. if version.crypto_revision exists, update it to that revision,
  118. otherwise update it to the default revision"""
  119. update_output = subprocess.check_output(
  120. [self.git_command, "submodule", "update", "--init", '--recursive'],
  121. cwd=git_worktree_path,
  122. stderr=subprocess.STDOUT
  123. )
  124. self.log.debug(update_output.decode("utf-8"))
  125. if not (os.path.exists(os.path.join(git_worktree_path, "crypto"))
  126. and version.crypto_revision):
  127. return
  128. if version.crypto_repository:
  129. fetch_output = subprocess.check_output(
  130. [self.git_command, "fetch", version.crypto_repository,
  131. version.crypto_revision],
  132. cwd=os.path.join(git_worktree_path, "crypto"),
  133. stderr=subprocess.STDOUT
  134. )
  135. self.log.debug(fetch_output.decode("utf-8"))
  136. crypto_rev = "FETCH_HEAD"
  137. else:
  138. crypto_rev = version.crypto_revision
  139. checkout_output = subprocess.check_output(
  140. [self.git_command, "checkout", crypto_rev],
  141. cwd=os.path.join(git_worktree_path, "crypto"),
  142. stderr=subprocess.STDOUT
  143. )
  144. self.log.debug(checkout_output.decode("utf-8"))
  145. def _build_shared_libraries(self, git_worktree_path, version):
  146. """Build the shared libraries in the specified worktree."""
  147. my_environment = os.environ.copy()
  148. my_environment["CFLAGS"] = "-g -Og"
  149. my_environment["SHARED"] = "1"
  150. if os.path.exists(os.path.join(git_worktree_path, "crypto")):
  151. my_environment["USE_CRYPTO_SUBMODULE"] = "1"
  152. make_output = subprocess.check_output(
  153. [self.make_command, "lib"],
  154. env=my_environment,
  155. cwd=git_worktree_path,
  156. stderr=subprocess.STDOUT
  157. )
  158. self.log.debug(make_output.decode("utf-8"))
  159. for root, _dirs, files in os.walk(git_worktree_path):
  160. for file in fnmatch.filter(files, "*.so"):
  161. version.modules[os.path.splitext(file)[0]] = (
  162. os.path.join(root, file)
  163. )
  164. @staticmethod
  165. def _pretty_revision(version):
  166. if version.revision == version.commit:
  167. return version.revision
  168. else:
  169. return "{} ({})".format(version.revision, version.commit)
  170. def _get_abi_dumps_from_shared_libraries(self, version):
  171. """Generate the ABI dumps for the specified git revision.
  172. The shared libraries must have been built and the module paths
  173. present in version.modules."""
  174. for mbed_module, module_path in version.modules.items():
  175. output_path = os.path.join(
  176. self.report_dir, "{}-{}-{}.dump".format(
  177. mbed_module, version.revision, version.version
  178. )
  179. )
  180. abi_dump_command = [
  181. "abi-dumper",
  182. module_path,
  183. "-o", output_path,
  184. "-lver", self._pretty_revision(version),
  185. ]
  186. abi_dump_output = subprocess.check_output(
  187. abi_dump_command,
  188. stderr=subprocess.STDOUT
  189. )
  190. self.log.debug(abi_dump_output.decode("utf-8"))
  191. version.abi_dumps[mbed_module] = output_path
  192. def _cleanup_worktree(self, git_worktree_path):
  193. """Remove the specified git worktree."""
  194. shutil.rmtree(git_worktree_path)
  195. worktree_output = subprocess.check_output(
  196. [self.git_command, "worktree", "prune"],
  197. cwd=self.repo_path,
  198. stderr=subprocess.STDOUT
  199. )
  200. self.log.debug(worktree_output.decode("utf-8"))
  201. def _get_abi_dump_for_ref(self, version):
  202. """Generate the ABI dumps for the specified git revision."""
  203. git_worktree_path = self._get_clean_worktree_for_git_revision(version)
  204. self._update_git_submodules(git_worktree_path, version)
  205. self._build_shared_libraries(git_worktree_path, version)
  206. self._get_abi_dumps_from_shared_libraries(version)
  207. self._cleanup_worktree(git_worktree_path)
  208. def _remove_children_with_tag(self, parent, tag):
  209. children = parent.getchildren()
  210. for child in children:
  211. if child.tag == tag:
  212. parent.remove(child)
  213. else:
  214. self._remove_children_with_tag(child, tag)
  215. def _remove_extra_detail_from_report(self, report_root):
  216. for tag in ['test_info', 'test_results', 'problem_summary',
  217. 'added_symbols', 'affected']:
  218. self._remove_children_with_tag(report_root, tag)
  219. for report in report_root:
  220. for problems in report.getchildren()[:]:
  221. if not problems.getchildren():
  222. report.remove(problems)
  223. def _abi_compliance_command(self, mbed_module, output_path):
  224. """Build the command to run to analyze the library mbed_module.
  225. The report will be placed in output_path."""
  226. abi_compliance_command = [
  227. "abi-compliance-checker",
  228. "-l", mbed_module,
  229. "-old", self.old_version.abi_dumps[mbed_module],
  230. "-new", self.new_version.abi_dumps[mbed_module],
  231. "-strict",
  232. "-report-path", output_path,
  233. ]
  234. if self.skip_file:
  235. abi_compliance_command += ["-skip-symbols", self.skip_file,
  236. "-skip-types", self.skip_file]
  237. if self.brief:
  238. abi_compliance_command += ["-report-format", "xml",
  239. "-stdout"]
  240. return abi_compliance_command
  241. def _is_library_compatible(self, mbed_module, compatibility_report):
  242. """Test if the library mbed_module has remained compatible.
  243. Append a message regarding compatibility to compatibility_report."""
  244. output_path = os.path.join(
  245. self.report_dir, "{}-{}-{}.html".format(
  246. mbed_module, self.old_version.revision,
  247. self.new_version.revision
  248. )
  249. )
  250. try:
  251. subprocess.check_output(
  252. self._abi_compliance_command(mbed_module, output_path),
  253. stderr=subprocess.STDOUT
  254. )
  255. except subprocess.CalledProcessError as err:
  256. if err.returncode != 1:
  257. raise err
  258. if self.brief:
  259. self.log.info(
  260. "Compatibility issues found for {}".format(mbed_module)
  261. )
  262. report_root = ET.fromstring(err.output.decode("utf-8"))
  263. self._remove_extra_detail_from_report(report_root)
  264. self.log.info(ET.tostring(report_root).decode("utf-8"))
  265. else:
  266. self.can_remove_report_dir = False
  267. compatibility_report.append(
  268. "Compatibility issues found for {}, "
  269. "for details see {}".format(mbed_module, output_path)
  270. )
  271. return False
  272. compatibility_report.append(
  273. "No compatibility issues for {}".format(mbed_module)
  274. )
  275. if not (self.keep_all_reports or self.brief):
  276. os.remove(output_path)
  277. return True
  278. def get_abi_compatibility_report(self):
  279. """Generate a report of the differences between the reference ABI
  280. and the new ABI. ABI dumps from self.old_version and self.new_version
  281. must be available."""
  282. compatibility_report = ["Checking evolution from {} to {}".format(
  283. self._pretty_revision(self.old_version),
  284. self._pretty_revision(self.new_version)
  285. )]
  286. compliance_return_code = 0
  287. shared_modules = list(set(self.old_version.modules.keys()) &
  288. set(self.new_version.modules.keys()))
  289. for mbed_module in shared_modules:
  290. if not self._is_library_compatible(mbed_module,
  291. compatibility_report):
  292. compliance_return_code = 1
  293. for version in [self.old_version, self.new_version]:
  294. for mbed_module, mbed_module_dump in version.abi_dumps.items():
  295. os.remove(mbed_module_dump)
  296. if self.can_remove_report_dir:
  297. os.rmdir(self.report_dir)
  298. self.log.info("\n".join(compatibility_report))
  299. return compliance_return_code
  300. def check_for_abi_changes(self):
  301. """Generate a report of ABI differences
  302. between self.old_rev and self.new_rev."""
  303. self.check_repo_path()
  304. self.check_abi_tools_are_installed()
  305. self._get_abi_dump_for_ref(self.old_version)
  306. self._get_abi_dump_for_ref(self.new_version)
  307. return self.get_abi_compatibility_report()
  308. def run_main():
  309. try:
  310. parser = argparse.ArgumentParser(
  311. description=(
  312. """This script is a small wrapper around the
  313. abi-compliance-checker and abi-dumper tools, applying them
  314. to compare the ABI and API of the library files from two
  315. different Git revisions within an Mbed TLS repository.
  316. The results of the comparison are either formatted as HTML and
  317. stored at a configurable location, or are given as a brief list
  318. of problems. Returns 0 on success, 1 on ABI/API non-compliance,
  319. and 2 if there is an error while running the script.
  320. Note: must be run from Mbed TLS root."""
  321. )
  322. )
  323. parser.add_argument(
  324. "-v", "--verbose", action="store_true",
  325. help="set verbosity level",
  326. )
  327. parser.add_argument(
  328. "-r", "--report-dir", type=str, default="reports",
  329. help="directory where reports are stored, default is reports",
  330. )
  331. parser.add_argument(
  332. "-k", "--keep-all-reports", action="store_true",
  333. help="keep all reports, even if there are no compatibility issues",
  334. )
  335. parser.add_argument(
  336. "-o", "--old-rev", type=str, help="revision for old version.",
  337. required=True,
  338. )
  339. parser.add_argument(
  340. "-or", "--old-repo", type=str, help="repository for old version."
  341. )
  342. parser.add_argument(
  343. "-oc", "--old-crypto-rev", type=str,
  344. help="revision for old crypto submodule."
  345. )
  346. parser.add_argument(
  347. "-ocr", "--old-crypto-repo", type=str,
  348. help="repository for old crypto submodule."
  349. )
  350. parser.add_argument(
  351. "-n", "--new-rev", type=str, help="revision for new version",
  352. required=True,
  353. )
  354. parser.add_argument(
  355. "-nr", "--new-repo", type=str, help="repository for new version."
  356. )
  357. parser.add_argument(
  358. "-nc", "--new-crypto-rev", type=str,
  359. help="revision for new crypto version"
  360. )
  361. parser.add_argument(
  362. "-ncr", "--new-crypto-repo", type=str,
  363. help="repository for new crypto submodule."
  364. )
  365. parser.add_argument(
  366. "-s", "--skip-file", type=str,
  367. help=("path to file containing symbols and types to skip "
  368. "(typically \"-s identifiers\" after running "
  369. "\"tests/scripts/list-identifiers.sh --internal\")")
  370. )
  371. parser.add_argument(
  372. "-b", "--brief", action="store_true",
  373. help="output only the list of issues to stdout, instead of a full report",
  374. )
  375. abi_args = parser.parse_args()
  376. if os.path.isfile(abi_args.report_dir):
  377. print("Error: {} is not a directory".format(abi_args.report_dir))
  378. parser.exit()
  379. old_version = SimpleNamespace(
  380. version="old",
  381. repository=abi_args.old_repo,
  382. revision=abi_args.old_rev,
  383. commit=None,
  384. crypto_repository=abi_args.old_crypto_repo,
  385. crypto_revision=abi_args.old_crypto_rev,
  386. abi_dumps={},
  387. modules={}
  388. )
  389. new_version = SimpleNamespace(
  390. version="new",
  391. repository=abi_args.new_repo,
  392. revision=abi_args.new_rev,
  393. commit=None,
  394. crypto_repository=abi_args.new_crypto_repo,
  395. crypto_revision=abi_args.new_crypto_rev,
  396. abi_dumps={},
  397. modules={}
  398. )
  399. configuration = SimpleNamespace(
  400. verbose=abi_args.verbose,
  401. report_dir=abi_args.report_dir,
  402. keep_all_reports=abi_args.keep_all_reports,
  403. brief=abi_args.brief,
  404. skip_file=abi_args.skip_file
  405. )
  406. abi_check = AbiChecker(old_version, new_version, configuration)
  407. return_code = abi_check.check_for_abi_changes()
  408. sys.exit(return_code)
  409. except Exception: # pylint: disable=broad-except
  410. # Print the backtrace and exit explicitly so as to exit with
  411. # status 2, not 1.
  412. traceback.print_exc()
  413. sys.exit(2)
  414. if __name__ == "__main__":
  415. run_main()