abi_check.py 17 KB

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