mach 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #!/usr/bin/env python
  2. #
  3. # This Source Code Form is subject to the terms of the Mozilla Public
  4. # License, v. 2.0. If a copy of the MPL was not distributed with this
  5. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. ##########################################################################
  7. #
  8. # This is a collection of helper tools to get stuff done in NSS.
  9. #
  10. import sys
  11. import argparse
  12. import fnmatch
  13. import io
  14. import subprocess
  15. import os
  16. import platform
  17. import shutil
  18. import tarfile
  19. import tempfile
  20. from hashlib import sha256
  21. DEVNULL = open(os.devnull, 'wb')
  22. cwd = os.path.dirname(os.path.abspath(__file__))
  23. def run_tests(test, cycles="standard", env={}, silent=False):
  24. domsuf = os.getenv('DOMSUF', "localdomain")
  25. host = os.getenv('HOST', "localhost")
  26. env = env.copy()
  27. env.update({
  28. "NSS_TESTS": test,
  29. "NSS_CYCLES": cycles,
  30. "DOMSUF": domsuf,
  31. "HOST": host
  32. })
  33. os_env = os.environ
  34. os_env.update(env)
  35. command = cwd + "/tests/all.sh"
  36. stdout = stderr = DEVNULL if silent else None
  37. subprocess.check_call(command, env=os_env, stdout=stdout, stderr=stderr)
  38. class coverityAction(argparse.Action):
  39. def get_coverity_remote_cfg(self):
  40. secret_name = 'project/relman/coverity-nss'
  41. secrets_url = 'http://taskcluster/secrets/v1/secret/{}'.format(secret_name)
  42. print('Using symbol upload token from the secrets service: "{}"'.
  43. format(secrets_url))
  44. import requests
  45. res = requests.get(secrets_url)
  46. res.raise_for_status()
  47. secret = res.json()
  48. cov_config = secret['secret'] if 'secret' in secret else None
  49. if cov_config is None:
  50. print('Ill formatted secret for Coverity. Aborting analysis.')
  51. return None
  52. return cov_config
  53. def get_coverity_local_cfg(self, path):
  54. try:
  55. import yaml
  56. file_handler = open(path)
  57. config = yaml.safe_load(file_handler)
  58. except Exception:
  59. print('Unable to load coverity config from {}'.format(path))
  60. return None
  61. return config
  62. def get_cov_config(self, path):
  63. cov_config = None
  64. if self.local_config:
  65. cov_config = self.get_coverity_local_cfg(path)
  66. else:
  67. cov_config = self.get_coverity_remote_cfg()
  68. if cov_config is None:
  69. print('Unable to load Coverity config.')
  70. return 1
  71. self.cov_analysis_url = cov_config.get('package_url')
  72. self.cov_package_name = cov_config.get('package_name')
  73. self.cov_url = cov_config.get('server_url')
  74. self.cov_port = cov_config.get('server_port')
  75. self.cov_auth = cov_config.get('auth_key')
  76. self.cov_package_ver = cov_config.get('package_ver')
  77. self.cov_full_stack = cov_config.get('full_stack', False)
  78. return 0
  79. def download_coverity(self):
  80. if self.cov_url is None or self.cov_port is None or self.cov_analysis_url is None or self.cov_auth is None:
  81. print('Missing Coverity config options!')
  82. return 1
  83. COVERITY_CONFIG = '''
  84. {
  85. "type": "Coverity configuration",
  86. "format_version": 1,
  87. "settings": {
  88. "server": {
  89. "host": "%s",
  90. "port": %s,
  91. "ssl" : true,
  92. "on_new_cert" : "trust",
  93. "auth_key_file": "%s"
  94. },
  95. "stream": "NSS",
  96. "cov_run_desktop": {
  97. "build_cmd": ["%s"],
  98. "clean_cmd": ["%s", "-cc"],
  99. }
  100. }
  101. }
  102. '''
  103. # Generate the coverity.conf and auth files
  104. build_cmd = os.path.join(cwd, 'build.sh')
  105. cov_auth_path = os.path.join(self.cov_state_path, 'auth')
  106. cov_setup_path = os.path.join(self.cov_state_path, 'coverity.conf')
  107. cov_conf = COVERITY_CONFIG % (self.cov_url, self.cov_port, cov_auth_path, build_cmd, build_cmd)
  108. def download(artifact_url, target):
  109. import requests
  110. resp = requests.get(artifact_url, verify=False, stream=True)
  111. resp.raise_for_status()
  112. # Extract archive into destination
  113. with tarfile.open(fileobj=io.BytesIO(resp.content)) as tar:
  114. tar.extractall(target)
  115. download(self.cov_analysis_url, self.cov_state_path)
  116. with open(cov_auth_path, 'w') as f:
  117. f.write(self.cov_auth)
  118. # Modify it's permission to 600
  119. os.chmod(cov_auth_path, 0o600)
  120. with open(cov_setup_path, 'a') as f:
  121. f.write(cov_conf)
  122. def setup_coverity(self, config_path, storage_path=None, force_download=True):
  123. rc = self.get_cov_config(config_path)
  124. if rc != 0:
  125. return rc
  126. if storage_path is None:
  127. # If storage_path is None we set the context of the coverity into the cwd.
  128. storage_path = cwd
  129. self.cov_state_path = os.path.join(storage_path, "coverity")
  130. if force_download is True or not os.path.exists(self.cov_state_path):
  131. shutil.rmtree(self.cov_state_path, ignore_errors=True)
  132. os.mkdir(self.cov_state_path)
  133. # Download everything that we need for Coverity from out private instance
  134. self.download_coverity()
  135. self.cov_path = os.path.join(self.cov_state_path, self.cov_package_name)
  136. self.cov_run_desktop = os.path.join(self.cov_path, 'bin', 'cov-run-desktop')
  137. self.cov_translate = os.path.join(self.cov_path, 'bin', 'cov-translate')
  138. self.cov_configure = os.path.join(self.cov_path, 'bin', 'cov-configure')
  139. self.cov_work_path = os.path.join(self.cov_state_path, 'data-coverity')
  140. self.cov_idir_path = os.path.join(self.cov_work_path, self.cov_package_ver, 'idir')
  141. if not os.path.exists(self.cov_path) or \
  142. not os.path.exists(self.cov_run_desktop) or \
  143. not os.path.exists(self.cov_translate) or \
  144. not os.path.exists(self.cov_configure):
  145. print('Missing Coverity in {}'.format(self.cov_path))
  146. return 1
  147. return 0
  148. def run_process(self, args, cwd=cwd):
  149. proc = subprocess.Popen(args, cwd=cwd)
  150. status = None
  151. while status is None:
  152. try:
  153. status = proc.wait()
  154. except KeyboardInterrupt:
  155. pass
  156. return status
  157. def cov_is_file_in_source(self, abs_path):
  158. if os.path.islink(abs_path):
  159. abs_path = os.path.realpath(abs_path)
  160. return abs_path
  161. def dump_cov_artifact(self, cov_results, source, output):
  162. import json
  163. def relpath(path):
  164. '''Build path relative to repository root'''
  165. if path.startswith(cwd):
  166. return os.path.relpath(path, cwd)
  167. return path
  168. # Parse Coverity json into structured issues
  169. with open(cov_results) as f:
  170. result = json.load(f)
  171. # Parse the issues to a standard json format
  172. issues_dict = {'files': {}}
  173. files_list = issues_dict['files']
  174. def build_element(issue):
  175. # We look only for main event
  176. event_path = next((event for event in issue['events'] if event['main'] is True), None)
  177. dict_issue = {
  178. 'line': issue['mainEventLineNumber'],
  179. 'flag': issue['checkerName'],
  180. 'message': event_path['eventDescription'],
  181. 'extra': {
  182. 'category': issue['checkerProperties']['category'],
  183. 'stateOnServer': issue['stateOnServer'],
  184. 'stack': []
  185. }
  186. }
  187. # Embed all events into extra message
  188. for event in issue['events']:
  189. dict_issue['extra']['stack'].append({'file_path': relpath(event['strippedFilePathname']),
  190. 'line_number': event['lineNumber'],
  191. 'path_type': event['eventTag'],
  192. 'description': event['eventDescription']})
  193. return dict_issue
  194. for issue in result['issues']:
  195. path = self.cov_is_file_in_source(issue['strippedMainEventFilePathname'])
  196. if path is None:
  197. # Since we skip a result we should log it
  198. print('Skipping CID: {0} from file: {1} since it\'s not related with the current patch.'.format(
  199. issue['stateOnServer']['cid'], issue['strippedMainEventFilePathname']))
  200. continue
  201. # If path does not start with `cwd` skip it
  202. if not path.startswith(cwd):
  203. continue
  204. path = relpath(path)
  205. if path in files_list:
  206. files_list[path]['warnings'].append(build_element(issue))
  207. else:
  208. files_list[path] = {'warnings': [build_element(issue)]}
  209. with open(output, 'w') as f:
  210. json.dump(issues_dict, f)
  211. def mutate_paths(self, paths):
  212. for index in xrange(len(paths)):
  213. paths[index] = os.path.abspath(paths[index])
  214. def __call__(self, parser, args, paths, option_string=None):
  215. self.local_config = True
  216. config_path = args.config
  217. storage_path = args.storage
  218. have_paths = True
  219. if len(paths) == 0:
  220. have_paths = False
  221. print('No files have been specified for analysis, running Coverity on the entire project.')
  222. self.mutate_paths(paths)
  223. if config_path is None:
  224. self.local_config = False
  225. print('No coverity config path has been specified, so running in automation.')
  226. if 'NSS_AUTOMATION' not in os.environ:
  227. print('Coverity based static-analysis cannot be ran outside automation.')
  228. return 1
  229. rc = self.setup_coverity(config_path, storage_path, args.force)
  230. if rc != 0:
  231. return 1
  232. # First run cov-run-desktop --setup in order to setup the analysis env
  233. cmd = [self.cov_run_desktop, '--setup']
  234. print('Running {} --setup'.format(self.cov_run_desktop))
  235. rc = self.run_process(args=cmd, cwd=self.cov_path)
  236. if rc != 0:
  237. print('Running {} --setup failed!'.format(self.cov_run_desktop))
  238. return rc
  239. cov_result = os.path.join(self.cov_state_path, 'cov-results.json')
  240. # Once the capture is performed we need to do the actual Coverity Desktop analysis
  241. if have_paths:
  242. cmd = [self.cov_run_desktop, '--json-output-v6', cov_result] + paths
  243. else:
  244. cmd = [self.cov_run_desktop, '--json-output-v6', cov_result, '--analyze-captured-source']
  245. print('Running Coverity Analysis for {}'.format(cmd))
  246. rc = self.run_process(cmd, cwd=self.cov_state_path)
  247. if rc != 0:
  248. print('Coverity Analysis failed!')
  249. # On automation, like try, we want to build an artifact with the results.
  250. if 'NSS_AUTOMATION' in os.environ:
  251. self.dump_cov_artifact(cov_result, cov_result, "/home/worker/nss/coverity/coverity.json")
  252. class cfAction(argparse.Action):
  253. docker_command = None
  254. restorecon = None
  255. def __call__(self, parser, args, values, option_string=None):
  256. self.setDockerCommand(args)
  257. if values:
  258. files = [os.path.relpath(os.path.abspath(x), start=cwd) for x in values]
  259. else:
  260. files = self.modifiedFiles()
  261. # First check if we can run docker.
  262. try:
  263. with open(os.devnull, "w") as f:
  264. subprocess.check_call(
  265. self.docker_command + ["images"], stdout=f)
  266. except:
  267. self.docker_command = None
  268. if self.docker_command is None:
  269. print("warning: running clang-format directly, which isn't guaranteed to be correct")
  270. command = [cwd + "/automation/clang-format/run_clang_format.sh"] + files
  271. repr(command)
  272. subprocess.call(command)
  273. return
  274. files = [os.path.join('/home/worker/nss', x) for x in files]
  275. docker_image = 'clang-format-service:latest'
  276. cf_docker_folder = cwd + "/automation/clang-format"
  277. # Build the image if necessary.
  278. if self.filesChanged(cf_docker_folder):
  279. self.buildImage(docker_image, cf_docker_folder)
  280. # Check if we have the docker image.
  281. try:
  282. command = self.docker_command + [
  283. "image", "inspect", "clang-format-service:latest"
  284. ]
  285. with open(os.devnull, "w") as f:
  286. subprocess.check_call(command, stdout=f)
  287. except:
  288. print("I have to build the docker image first.")
  289. self.buildImage(docker_image, cf_docker_folder)
  290. command = self.docker_command + [
  291. 'run', '-v', cwd + ':/home/worker/nss:Z', '--rm', '-ti', docker_image
  292. ]
  293. # The clang format script returns 1 if something's to do. We don't
  294. # care.
  295. subprocess.call(command + files)
  296. if self.restorecon is not None:
  297. subprocess.call([self.restorecon, '-R', cwd])
  298. def filesChanged(self, path):
  299. hash = sha256()
  300. for dirname, dirnames, files in os.walk(path):
  301. for file in files:
  302. with open(os.path.join(dirname, file), "rb") as f:
  303. hash.update(f.read())
  304. chk_file = cwd + "/.chk"
  305. old_chk = ""
  306. new_chk = hash.hexdigest()
  307. if os.path.exists(chk_file):
  308. with open(chk_file) as f:
  309. old_chk = f.readline()
  310. if old_chk != new_chk:
  311. with open(chk_file, "w+") as f:
  312. f.write(new_chk)
  313. return True
  314. return False
  315. def buildImage(self, docker_image, cf_docker_folder):
  316. command = self.docker_command + [
  317. "build", "-t", docker_image, cf_docker_folder
  318. ]
  319. subprocess.check_call(command)
  320. return
  321. def setDockerCommand(self, args):
  322. from distutils.spawn import find_executable
  323. if platform.system() == "Linux":
  324. self.restorecon = find_executable("restorecon")
  325. dcmd = find_executable("docker")
  326. if dcmd is not None:
  327. self.docker_command = [dcmd]
  328. if not args.noroot:
  329. self.docker_command = ["sudo"] + self.docker_command
  330. else:
  331. self.docker_command = None
  332. def modifiedFiles(self):
  333. files = []
  334. if os.path.exists(os.path.join(cwd, '.hg')):
  335. st = subprocess.Popen(['hg', 'status', '-m', '-a'],
  336. cwd=cwd, stdout=subprocess.PIPE, universal_newlines=True)
  337. for line in iter(st.stdout.readline, ''):
  338. files += [line[2:].rstrip()]
  339. elif os.path.exists(os.path.join(cwd, '.git')):
  340. st = subprocess.Popen(['git', 'status', '--porcelain'],
  341. cwd=cwd, stdout=subprocess.PIPE)
  342. for line in iter(st.stdout.readline, ''):
  343. if line[1] == 'M' or line[1] != 'D' and \
  344. (line[0] == 'M' or line[0] == 'A' or
  345. line[0] == 'C' or line[0] == 'U'):
  346. files += [line[3:].rstrip()]
  347. elif line[0] == 'R':
  348. files += [line[line.index(' -> ', beg=4) + 4:]]
  349. else:
  350. print('Warning: neither mercurial nor git detected!')
  351. def isFormatted(x):
  352. return x[-2:] == '.c' or x[-3:] == '.cc' or x[-2:] == '.h'
  353. return [x for x in files if isFormatted(x)]
  354. class buildAction(argparse.Action):
  355. def __call__(self, parser, args, values, option_string=None):
  356. subprocess.check_call([cwd + "/build.sh"] + values)
  357. class testAction(argparse.Action):
  358. def __call__(self, parser, args, values, option_string=None):
  359. run_tests(values)
  360. class covAction(argparse.Action):
  361. def runSslGtests(self, outdir):
  362. env = {
  363. "GTESTFILTER": "*", # Prevent parallel test runs.
  364. "ASAN_OPTIONS": "coverage=1:coverage_dir=" + outdir,
  365. "NSS_DEFAULT_DB_TYPE": "dbm"
  366. }
  367. run_tests("ssl_gtests", env=env, silent=True)
  368. def findSanCovFile(self, outdir):
  369. for file in os.listdir(outdir):
  370. if fnmatch.fnmatch(file, 'ssl_gtest.*.sancov'):
  371. return os.path.join(outdir, file)
  372. return None
  373. def __call__(self, parser, args, values, option_string=None):
  374. outdir = args.outdir
  375. print("Output directory: " + outdir)
  376. print("\nBuild with coverage sanitizers...\n")
  377. sancov_args = "edge,no-prune,trace-pc-guard,trace-cmp"
  378. subprocess.check_call([
  379. os.path.join(cwd, "build.sh"), "-c", "--clang", "--asan", "--enable-legacy-db",
  380. "--sancov=" + sancov_args
  381. ])
  382. print("\nRun ssl_gtests to get a coverage report...")
  383. self.runSslGtests(outdir)
  384. print("Done.")
  385. sancov_file = self.findSanCovFile(outdir)
  386. if not sancov_file:
  387. print("Couldn't find .sancov file.")
  388. sys.exit(1)
  389. symcov_file = os.path.join(outdir, "ssl_gtest.symcov")
  390. out = open(symcov_file, 'wb')
  391. # Don't exit immediately on error
  392. symbol_retcode = subprocess.call([
  393. "sancov",
  394. "-blacklist=" + os.path.join(cwd, ".sancov-blacklist"),
  395. "-symbolize", sancov_file,
  396. os.path.join(cwd, "../dist/Debug/bin/ssl_gtest")
  397. ], stdout=out)
  398. out.close()
  399. print("\nCopying ssl_gtests to artifacts...")
  400. shutil.copyfile(os.path.join(cwd, "../dist/Debug/bin/ssl_gtest"),
  401. os.path.join(outdir, "ssl_gtest"))
  402. print("\nCoverage report: " + symcov_file)
  403. if symbol_retcode > 0:
  404. print("sancov failed to symbolize with return code {}".format(symbol_retcode))
  405. sys.exit(symbol_retcode)
  406. class commandsAction(argparse.Action):
  407. commands = []
  408. def __call__(self, parser, args, values, option_string=None):
  409. for c in commandsAction.commands:
  410. print(c)
  411. def parse_arguments():
  412. parser = argparse.ArgumentParser(
  413. description='NSS helper script. ' +
  414. 'Make sure to separate sub-command arguments with --.')
  415. subparsers = parser.add_subparsers()
  416. parser_build = subparsers.add_parser(
  417. 'build', help='All arguments are passed to build.sh')
  418. parser_build.add_argument(
  419. 'build_args', nargs='*', help="build arguments", action=buildAction)
  420. parser_cf = subparsers.add_parser(
  421. 'clang-format',
  422. help="""
  423. Run clang-format.
  424. By default this runs against any files that you have modified. If
  425. there are no modified files, it checks everything.
  426. """)
  427. parser_cf.add_argument(
  428. '--noroot',
  429. help='On linux, suppress the use of \'sudo\' for running docker.',
  430. action='store_true')
  431. parser_cf.add_argument(
  432. '<file/dir>',
  433. nargs='*',
  434. help="Specify files or directories to run clang-format on",
  435. action=cfAction)
  436. parser_sa = subparsers.add_parser(
  437. 'static-analysis',
  438. help="""
  439. Run static-analysis tools based on coverity.
  440. By default this runs only on automation and provides a list of issues that
  441. are only present locally.
  442. """)
  443. parser_sa.add_argument(
  444. '--config', help='Path to Coverity config file. Only used for local runs.',
  445. default=None)
  446. parser_sa.add_argument(
  447. '--storage', help="""
  448. Path where to store Coverity binaries and results. If none, the base repository will be used.
  449. """,
  450. default=None)
  451. parser_sa.add_argument(
  452. '--force', help='Force the re-download of the coverity artefact.',
  453. action='store_true')
  454. parser_sa.add_argument(
  455. '<file>',
  456. nargs='*',
  457. help="Specify files to run Coverity on. If no files are specified the analysis will check the entire project.",
  458. action=coverityAction)
  459. parser_test = subparsers.add_parser(
  460. 'tests', help='Run tests through tests/all.sh.')
  461. tests = [
  462. "cipher", "lowhash", "chains", "cert", "dbtests", "tools", "fips",
  463. "sdr", "crmf", "smime", "ssl", "ocsp", "merge", "pkits", "ec",
  464. "gtests", "ssl_gtests", "bogo", "interop", "policy"
  465. ]
  466. parser_test.add_argument(
  467. 'test', choices=tests, help="Available tests", action=testAction)
  468. parser_cov = subparsers.add_parser(
  469. 'coverage', help='Generate coverage report')
  470. cov_modules = ["ssl_gtests"]
  471. parser_cov.add_argument(
  472. '--outdir', help='Output directory for coverage report data.',
  473. default=tempfile.mkdtemp())
  474. parser_cov.add_argument(
  475. 'module', choices=cov_modules, help="Available coverage modules",
  476. action=covAction)
  477. parser_commands = subparsers.add_parser(
  478. 'mach-completion',
  479. help="list commands")
  480. parser_commands.add_argument(
  481. 'mach-completion',
  482. nargs='*',
  483. action=commandsAction)
  484. commandsAction.commands = [c for c in subparsers.choices]
  485. return parser.parse_args()
  486. def main():
  487. parse_arguments()
  488. if __name__ == '__main__':
  489. main()