PageRenderTime 25ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/clang/tools/scan-build-py/libscanbuild/analyze.py

https://gitlab.com/williamwp/riscv-rv32x-llvm
Python | 780 lines | 776 code | 0 blank | 4 comment | 2 complexity | 144b749dfa8d39744f98478833186aad MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  3. # See https://llvm.org/LICENSE.txt for license information.
  4. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. """ This module implements the 'scan-build' command API.
  6. To run the static analyzer against a build is done in multiple steps:
  7. -- Intercept: capture the compilation command during the build,
  8. -- Analyze: run the analyzer against the captured commands,
  9. -- Report: create a cover report from the analyzer outputs. """
  10. import re
  11. import os
  12. import os.path
  13. import json
  14. import logging
  15. import multiprocessing
  16. import tempfile
  17. import functools
  18. import subprocess
  19. import contextlib
  20. import datetime
  21. import shutil
  22. import glob
  23. from collections import defaultdict
  24. from libscanbuild import command_entry_point, compiler_wrapper, \
  25. wrapper_environment, run_build, run_command, CtuConfig
  26. from libscanbuild.arguments import parse_args_for_scan_build, \
  27. parse_args_for_analyze_build
  28. from libscanbuild.intercept import capture
  29. from libscanbuild.report import document
  30. from libscanbuild.compilation import split_command, classify_source, \
  31. compiler_language
  32. from libscanbuild.clang import get_version, get_arguments, get_triple_arch
  33. from libscanbuild.shell import decode
  34. __all__ = ['scan_build', 'analyze_build', 'analyze_compiler_wrapper']
  35. COMPILER_WRAPPER_CC = 'analyze-cc'
  36. COMPILER_WRAPPER_CXX = 'analyze-c++'
  37. CTU_EXTDEF_MAP_FILENAME = 'externalDefMap.txt'
  38. CTU_TEMP_DEFMAP_FOLDER = 'tmpExternalDefMaps'
  39. @command_entry_point
  40. def scan_build():
  41. """ Entry point for scan-build command. """
  42. args = parse_args_for_scan_build()
  43. # will re-assign the report directory as new output
  44. with report_directory(args.output, args.keep_empty) as args.output:
  45. # Run against a build command. there are cases, when analyzer run
  46. # is not required. But we need to set up everything for the
  47. # wrappers, because 'configure' needs to capture the CC/CXX values
  48. # for the Makefile.
  49. if args.intercept_first:
  50. # Run build command with intercept module.
  51. exit_code = capture(args)
  52. # Run the analyzer against the captured commands.
  53. if need_analyzer(args.build):
  54. govern_analyzer_runs(args)
  55. else:
  56. # Run build command and analyzer with compiler wrappers.
  57. environment = setup_environment(args)
  58. exit_code = run_build(args.build, env=environment)
  59. # Cover report generation and bug counting.
  60. number_of_bugs = document(args)
  61. # Set exit status as it was requested.
  62. return number_of_bugs if args.status_bugs else exit_code
  63. @command_entry_point
  64. def analyze_build():
  65. """ Entry point for analyze-build command. """
  66. args = parse_args_for_analyze_build()
  67. # will re-assign the report directory as new output
  68. with report_directory(args.output, args.keep_empty) as args.output:
  69. # Run the analyzer against a compilation db.
  70. govern_analyzer_runs(args)
  71. # Cover report generation and bug counting.
  72. number_of_bugs = document(args)
  73. # Set exit status as it was requested.
  74. return number_of_bugs if args.status_bugs else 0
  75. def need_analyzer(args):
  76. """ Check the intent of the build command.
  77. When static analyzer run against project configure step, it should be
  78. silent and no need to run the analyzer or generate report.
  79. To run `scan-build` against the configure step might be necessary,
  80. when compiler wrappers are used. That's the moment when build setup
  81. check the compiler and capture the location for the build process. """
  82. return len(args) and not re.search(r'configure|autogen', args[0])
  83. def prefix_with(constant, pieces):
  84. """ From a sequence create another sequence where every second element
  85. is from the original sequence and the odd elements are the prefix.
  86. eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """
  87. return [elem for piece in pieces for elem in [constant, piece]]
  88. def get_ctu_config_from_args(args):
  89. """ CTU configuration is created from the chosen phases and dir. """
  90. return (
  91. CtuConfig(collect=args.ctu_phases.collect,
  92. analyze=args.ctu_phases.analyze,
  93. dir=args.ctu_dir,
  94. extdef_map_cmd=args.extdef_map_cmd)
  95. if hasattr(args, 'ctu_phases') and hasattr(args.ctu_phases, 'dir')
  96. else CtuConfig(collect=False, analyze=False, dir='', extdef_map_cmd=''))
  97. def get_ctu_config_from_json(ctu_conf_json):
  98. """ CTU configuration is created from the chosen phases and dir. """
  99. ctu_config = json.loads(ctu_conf_json)
  100. # Recover namedtuple from json when coming from analyze-cc or analyze-c++
  101. return CtuConfig(collect=ctu_config[0],
  102. analyze=ctu_config[1],
  103. dir=ctu_config[2],
  104. extdef_map_cmd=ctu_config[3])
  105. def create_global_ctu_extdef_map(extdef_map_lines):
  106. """ Takes iterator of individual external definition maps and creates a
  107. global map keeping only unique names. We leave conflicting names out of
  108. CTU.
  109. :param extdef_map_lines: Contains the id of a definition (mangled name) and
  110. the originating source (the corresponding AST file) name.
  111. :type extdef_map_lines: Iterator of str.
  112. :returns: Mangled name - AST file pairs.
  113. :rtype: List of (str, str) tuples.
  114. """
  115. mangled_to_asts = defaultdict(set)
  116. for line in extdef_map_lines:
  117. mangled_name, ast_file = line.strip().split(' ', 1)
  118. mangled_to_asts[mangled_name].add(ast_file)
  119. mangled_ast_pairs = []
  120. for mangled_name, ast_files in mangled_to_asts.items():
  121. if len(ast_files) == 1:
  122. mangled_ast_pairs.append((mangled_name, next(iter(ast_files))))
  123. return mangled_ast_pairs
  124. def merge_ctu_extdef_maps(ctudir):
  125. """ Merge individual external definition maps into a global one.
  126. As the collect phase runs parallel on multiple threads, all compilation
  127. units are separately mapped into a temporary file in CTU_TEMP_DEFMAP_FOLDER.
  128. These definition maps contain the mangled names and the source
  129. (AST generated from the source) which had their definition.
  130. These files should be merged at the end into a global map file:
  131. CTU_EXTDEF_MAP_FILENAME."""
  132. def generate_extdef_map_lines(extdefmap_dir):
  133. """ Iterate over all lines of input files in a determined order. """
  134. files = glob.glob(os.path.join(extdefmap_dir, '*'))
  135. files.sort()
  136. for filename in files:
  137. with open(filename, 'r') as in_file:
  138. for line in in_file:
  139. yield line
  140. def write_global_map(arch, mangled_ast_pairs):
  141. """ Write (mangled name, ast file) pairs into final file. """
  142. extern_defs_map_file = os.path.join(ctudir, arch,
  143. CTU_EXTDEF_MAP_FILENAME)
  144. with open(extern_defs_map_file, 'w') as out_file:
  145. for mangled_name, ast_file in mangled_ast_pairs:
  146. out_file.write('%s %s\n' % (mangled_name, ast_file))
  147. triple_arches = glob.glob(os.path.join(ctudir, '*'))
  148. for triple_path in triple_arches:
  149. if os.path.isdir(triple_path):
  150. triple_arch = os.path.basename(triple_path)
  151. extdefmap_dir = os.path.join(ctudir, triple_arch,
  152. CTU_TEMP_DEFMAP_FOLDER)
  153. extdef_map_lines = generate_extdef_map_lines(extdefmap_dir)
  154. mangled_ast_pairs = create_global_ctu_extdef_map(extdef_map_lines)
  155. write_global_map(triple_arch, mangled_ast_pairs)
  156. # Remove all temporary files
  157. shutil.rmtree(extdefmap_dir, ignore_errors=True)
  158. def run_analyzer_parallel(args):
  159. """ Runs the analyzer against the given compilation database. """
  160. def exclude(filename):
  161. """ Return true when any excluded directory prefix the filename. """
  162. return any(re.match(r'^' + directory, filename)
  163. for directory in args.excludes)
  164. consts = {
  165. 'clang': args.clang,
  166. 'output_dir': args.output,
  167. 'output_format': args.output_format,
  168. 'output_failures': args.output_failures,
  169. 'direct_args': analyzer_params(args),
  170. 'force_debug': args.force_debug,
  171. 'ctu': get_ctu_config_from_args(args)
  172. }
  173. logging.debug('run analyzer against compilation database')
  174. with open(args.cdb, 'r') as handle:
  175. generator = (dict(cmd, **consts)
  176. for cmd in json.load(handle) if not exclude(cmd['file']))
  177. # when verbose output requested execute sequentially
  178. pool = multiprocessing.Pool(1 if args.verbose > 2 else None)
  179. for current in pool.imap_unordered(run, generator):
  180. if current is not None:
  181. # display error message from the static analyzer
  182. for line in current['error_output']:
  183. logging.info(line.rstrip())
  184. pool.close()
  185. pool.join()
  186. def govern_analyzer_runs(args):
  187. """ Governs multiple runs in CTU mode or runs once in normal mode. """
  188. ctu_config = get_ctu_config_from_args(args)
  189. # If we do a CTU collect (1st phase) we remove all previous collection
  190. # data first.
  191. if ctu_config.collect:
  192. shutil.rmtree(ctu_config.dir, ignore_errors=True)
  193. # If the user asked for a collect (1st) and analyze (2nd) phase, we do an
  194. # all-in-one run where we deliberately remove collection data before and
  195. # also after the run. If the user asks only for a single phase data is
  196. # left so multiple analyze runs can use the same data gathered by a single
  197. # collection run.
  198. if ctu_config.collect and ctu_config.analyze:
  199. # CTU strings are coming from args.ctu_dir and extdef_map_cmd,
  200. # so we can leave it empty
  201. args.ctu_phases = CtuConfig(collect=True, analyze=False,
  202. dir='', extdef_map_cmd='')
  203. run_analyzer_parallel(args)
  204. merge_ctu_extdef_maps(ctu_config.dir)
  205. args.ctu_phases = CtuConfig(collect=False, analyze=True,
  206. dir='', extdef_map_cmd='')
  207. run_analyzer_parallel(args)
  208. shutil.rmtree(ctu_config.dir, ignore_errors=True)
  209. else:
  210. # Single runs (collect or analyze) are launched from here.
  211. run_analyzer_parallel(args)
  212. if ctu_config.collect:
  213. merge_ctu_extdef_maps(ctu_config.dir)
  214. def setup_environment(args):
  215. """ Set up environment for build command to interpose compiler wrapper. """
  216. environment = dict(os.environ)
  217. environment.update(wrapper_environment(args))
  218. environment.update({
  219. 'CC': COMPILER_WRAPPER_CC,
  220. 'CXX': COMPILER_WRAPPER_CXX,
  221. 'ANALYZE_BUILD_CLANG': args.clang if need_analyzer(args.build) else '',
  222. 'ANALYZE_BUILD_REPORT_DIR': args.output,
  223. 'ANALYZE_BUILD_REPORT_FORMAT': args.output_format,
  224. 'ANALYZE_BUILD_REPORT_FAILURES': 'yes' if args.output_failures else '',
  225. 'ANALYZE_BUILD_PARAMETERS': ' '.join(analyzer_params(args)),
  226. 'ANALYZE_BUILD_FORCE_DEBUG': 'yes' if args.force_debug else '',
  227. 'ANALYZE_BUILD_CTU': json.dumps(get_ctu_config_from_args(args))
  228. })
  229. return environment
  230. @command_entry_point
  231. def analyze_compiler_wrapper():
  232. """ Entry point for `analyze-cc` and `analyze-c++` compiler wrappers. """
  233. return compiler_wrapper(analyze_compiler_wrapper_impl)
  234. def analyze_compiler_wrapper_impl(result, execution):
  235. """ Implements analyzer compiler wrapper functionality. """
  236. # don't run analyzer when compilation fails. or when it's not requested.
  237. if result or not os.getenv('ANALYZE_BUILD_CLANG'):
  238. return
  239. # check is it a compilation?
  240. compilation = split_command(execution.cmd)
  241. if compilation is None:
  242. return
  243. # collect the needed parameters from environment, crash when missing
  244. parameters = {
  245. 'clang': os.getenv('ANALYZE_BUILD_CLANG'),
  246. 'output_dir': os.getenv('ANALYZE_BUILD_REPORT_DIR'),
  247. 'output_format': os.getenv('ANALYZE_BUILD_REPORT_FORMAT'),
  248. 'output_failures': os.getenv('ANALYZE_BUILD_REPORT_FAILURES'),
  249. 'direct_args': os.getenv('ANALYZE_BUILD_PARAMETERS',
  250. '').split(' '),
  251. 'force_debug': os.getenv('ANALYZE_BUILD_FORCE_DEBUG'),
  252. 'directory': execution.cwd,
  253. 'command': [execution.cmd[0], '-c'] + compilation.flags,
  254. 'ctu': get_ctu_config_from_json(os.getenv('ANALYZE_BUILD_CTU'))
  255. }
  256. # call static analyzer against the compilation
  257. for source in compilation.files:
  258. parameters.update({'file': source})
  259. logging.debug('analyzer parameters %s', parameters)
  260. current = run(parameters)
  261. # display error message from the static analyzer
  262. if current is not None:
  263. for line in current['error_output']:
  264. logging.info(line.rstrip())
  265. @contextlib.contextmanager
  266. def report_directory(hint, keep):
  267. """ Responsible for the report directory.
  268. hint -- could specify the parent directory of the output directory.
  269. keep -- a boolean value to keep or delete the empty report directory. """
  270. stamp_format = 'scan-build-%Y-%m-%d-%H-%M-%S-%f-'
  271. stamp = datetime.datetime.now().strftime(stamp_format)
  272. parent_dir = os.path.abspath(hint)
  273. if not os.path.exists(parent_dir):
  274. os.makedirs(parent_dir)
  275. name = tempfile.mkdtemp(prefix=stamp, dir=parent_dir)
  276. logging.info('Report directory created: %s', name)
  277. try:
  278. yield name
  279. finally:
  280. if os.listdir(name):
  281. msg = "Run 'scan-view %s' to examine bug reports."
  282. keep = True
  283. else:
  284. if keep:
  285. msg = "Report directory '%s' contains no report, but kept."
  286. else:
  287. msg = "Removing directory '%s' because it contains no report."
  288. logging.warning(msg, name)
  289. if not keep:
  290. os.rmdir(name)
  291. def analyzer_params(args):
  292. """ A group of command line arguments can mapped to command
  293. line arguments of the analyzer. This method generates those. """
  294. result = []
  295. if args.store_model:
  296. result.append('-analyzer-store={0}'.format(args.store_model))
  297. if args.constraints_model:
  298. result.append('-analyzer-constraints={0}'.format(
  299. args.constraints_model))
  300. if args.internal_stats:
  301. result.append('-analyzer-stats')
  302. if args.analyze_headers:
  303. result.append('-analyzer-opt-analyze-headers')
  304. if args.stats:
  305. result.append('-analyzer-checker=debug.Stats')
  306. if args.maxloop:
  307. result.extend(['-analyzer-max-loop', str(args.maxloop)])
  308. if args.output_format:
  309. result.append('-analyzer-output={0}'.format(args.output_format))
  310. if args.analyzer_config:
  311. result.extend(['-analyzer-config', args.analyzer_config])
  312. if args.verbose >= 4:
  313. result.append('-analyzer-display-progress')
  314. if args.plugins:
  315. result.extend(prefix_with('-load', args.plugins))
  316. if args.enable_checker:
  317. checkers = ','.join(args.enable_checker)
  318. result.extend(['-analyzer-checker', checkers])
  319. if args.disable_checker:
  320. checkers = ','.join(args.disable_checker)
  321. result.extend(['-analyzer-disable-checker', checkers])
  322. return prefix_with('-Xclang', result)
  323. def require(required):
  324. """ Decorator for checking the required values in state.
  325. It checks the required attributes in the passed state and stop when
  326. any of those is missing. """
  327. def decorator(function):
  328. @functools.wraps(function)
  329. def wrapper(*args, **kwargs):
  330. for key in required:
  331. if key not in args[0]:
  332. raise KeyError('{0} not passed to {1}'.format(
  333. key, function.__name__))
  334. return function(*args, **kwargs)
  335. return wrapper
  336. return decorator
  337. @require(['command', # entry from compilation database
  338. 'directory', # entry from compilation database
  339. 'file', # entry from compilation database
  340. 'clang', # clang executable name (and path)
  341. 'direct_args', # arguments from command line
  342. 'force_debug', # kill non debug macros
  343. 'output_dir', # where generated report files shall go
  344. 'output_format', # it's 'plist', 'html', both or plist-multi-file
  345. 'output_failures', # generate crash reports or not
  346. 'ctu']) # ctu control options
  347. def run(opts):
  348. """ Entry point to run (or not) static analyzer against a single entry
  349. of the compilation database.
  350. This complex task is decomposed into smaller methods which are calling
  351. each other in chain. If the analyzis is not possible the given method
  352. just return and break the chain.
  353. The passed parameter is a python dictionary. Each method first check
  354. that the needed parameters received. (This is done by the 'require'
  355. decorator. It's like an 'assert' to check the contract between the
  356. caller and the called method.) """
  357. try:
  358. command = opts.pop('command')
  359. command = command if isinstance(command, list) else decode(command)
  360. logging.debug("Run analyzer against '%s'", command)
  361. opts.update(classify_parameters(command))
  362. return arch_check(opts)
  363. except Exception:
  364. logging.error("Problem occurred during analyzis.", exc_info=1)
  365. return None
  366. @require(['clang', 'directory', 'flags', 'file', 'output_dir', 'language',
  367. 'error_output', 'exit_code'])
  368. def report_failure(opts):
  369. """ Create report when analyzer failed.
  370. The major report is the preprocessor output. The output filename generated
  371. randomly. The compiler output also captured into '.stderr.txt' file.
  372. And some more execution context also saved into '.info.txt' file. """
  373. def extension():
  374. """ Generate preprocessor file extension. """
  375. mapping = {'objective-c++': '.mii', 'objective-c': '.mi', 'c++': '.ii'}
  376. return mapping.get(opts['language'], '.i')
  377. def destination():
  378. """ Creates failures directory if not exits yet. """
  379. failures_dir = os.path.join(opts['output_dir'], 'failures')
  380. if not os.path.isdir(failures_dir):
  381. os.makedirs(failures_dir)
  382. return failures_dir
  383. # Classify error type: when Clang terminated by a signal it's a 'Crash'.
  384. # (python subprocess Popen.returncode is negative when child terminated
  385. # by signal.) Everything else is 'Other Error'.
  386. error = 'crash' if opts['exit_code'] < 0 else 'other_error'
  387. # Create preprocessor output file name. (This is blindly following the
  388. # Perl implementation.)
  389. (handle, name) = tempfile.mkstemp(suffix=extension(),
  390. prefix='clang_' + error + '_',
  391. dir=destination())
  392. os.close(handle)
  393. # Execute Clang again, but run the syntax check only.
  394. cwd = opts['directory']
  395. cmd = get_arguments(
  396. [opts['clang'], '-fsyntax-only', '-E'
  397. ] + opts['flags'] + [opts['file'], '-o', name], cwd)
  398. run_command(cmd, cwd=cwd)
  399. # write general information about the crash
  400. with open(name + '.info.txt', 'w') as handle:
  401. handle.write(opts['file'] + os.linesep)
  402. handle.write(error.title().replace('_', ' ') + os.linesep)
  403. handle.write(' '.join(cmd) + os.linesep)
  404. handle.write(' '.join(os.uname()) + os.linesep)
  405. handle.write(get_version(opts['clang']))
  406. handle.close()
  407. # write the captured output too
  408. with open(name + '.stderr.txt', 'w') as handle:
  409. handle.writelines(opts['error_output'])
  410. handle.close()
  411. @require(['clang', 'directory', 'flags', 'direct_args', 'file', 'output_dir',
  412. 'output_format'])
  413. def run_analyzer(opts, continuation=report_failure):
  414. """ It assembles the analysis command line and executes it. Capture the
  415. output of the analysis and returns with it. If failure reports are
  416. requested, it calls the continuation to generate it. """
  417. def target():
  418. """ Creates output file name for reports. """
  419. if opts['output_format'] in {
  420. 'plist',
  421. 'plist-html',
  422. 'plist-multi-file'}:
  423. (handle, name) = tempfile.mkstemp(prefix='report-',
  424. suffix='.plist',
  425. dir=opts['output_dir'])
  426. os.close(handle)
  427. return name
  428. return opts['output_dir']
  429. try:
  430. cwd = opts['directory']
  431. cmd = get_arguments([opts['clang'], '--analyze'] +
  432. opts['direct_args'] + opts['flags'] +
  433. [opts['file'], '-o', target()],
  434. cwd)
  435. output = run_command(cmd, cwd=cwd)
  436. return {'error_output': output, 'exit_code': 0}
  437. except subprocess.CalledProcessError as ex:
  438. result = {'error_output': ex.output, 'exit_code': ex.returncode}
  439. if opts.get('output_failures', False):
  440. opts.update(result)
  441. continuation(opts)
  442. return result
  443. def extdef_map_list_src_to_ast(extdef_src_list):
  444. """ Turns textual external definition map list with source files into an
  445. external definition map list with ast files. """
  446. extdef_ast_list = []
  447. for extdef_src_txt in extdef_src_list:
  448. mangled_name, path = extdef_src_txt.split(" ", 1)
  449. # Normalize path on windows as well
  450. path = os.path.splitdrive(path)[1]
  451. # Make relative path out of absolute
  452. path = path[1:] if path[0] == os.sep else path
  453. ast_path = os.path.join("ast", path + ".ast")
  454. extdef_ast_list.append(mangled_name + " " + ast_path)
  455. return extdef_ast_list
  456. @require(['clang', 'directory', 'flags', 'direct_args', 'file', 'ctu'])
  457. def ctu_collect_phase(opts):
  458. """ Preprocess source by generating all data needed by CTU analysis. """
  459. def generate_ast(triple_arch):
  460. """ Generates ASTs for the current compilation command. """
  461. args = opts['direct_args'] + opts['flags']
  462. ast_joined_path = os.path.join(opts['ctu'].dir, triple_arch, 'ast',
  463. os.path.realpath(opts['file'])[1:] +
  464. '.ast')
  465. ast_path = os.path.abspath(ast_joined_path)
  466. ast_dir = os.path.dirname(ast_path)
  467. if not os.path.isdir(ast_dir):
  468. try:
  469. os.makedirs(ast_dir)
  470. except OSError:
  471. # In case an other process already created it.
  472. pass
  473. ast_command = [opts['clang'], '-emit-ast']
  474. ast_command.extend(args)
  475. ast_command.append('-w')
  476. ast_command.append(opts['file'])
  477. ast_command.append('-o')
  478. ast_command.append(ast_path)
  479. logging.debug("Generating AST using '%s'", ast_command)
  480. run_command(ast_command, cwd=opts['directory'])
  481. def map_extdefs(triple_arch):
  482. """ Generate external definition map file for the current source. """
  483. args = opts['direct_args'] + opts['flags']
  484. extdefmap_command = [opts['ctu'].extdef_map_cmd]
  485. extdefmap_command.append(opts['file'])
  486. extdefmap_command.append('--')
  487. extdefmap_command.extend(args)
  488. logging.debug("Generating external definition map using '%s'",
  489. extdefmap_command)
  490. extdef_src_list = run_command(extdefmap_command, cwd=opts['directory'])
  491. extdef_ast_list = extdef_map_list_src_to_ast(extdef_src_list)
  492. extern_defs_map_folder = os.path.join(opts['ctu'].dir, triple_arch,
  493. CTU_TEMP_DEFMAP_FOLDER)
  494. if not os.path.isdir(extern_defs_map_folder):
  495. try:
  496. os.makedirs(extern_defs_map_folder)
  497. except OSError:
  498. # In case an other process already created it.
  499. pass
  500. if extdef_ast_list:
  501. with tempfile.NamedTemporaryFile(mode='w',
  502. dir=extern_defs_map_folder,
  503. delete=False) as out_file:
  504. out_file.write("\n".join(extdef_ast_list) + "\n")
  505. cwd = opts['directory']
  506. cmd = [opts['clang'], '--analyze'] + opts['direct_args'] + opts['flags'] \
  507. + [opts['file']]
  508. triple_arch = get_triple_arch(cmd, cwd)
  509. generate_ast(triple_arch)
  510. map_extdefs(triple_arch)
  511. @require(['ctu'])
  512. def dispatch_ctu(opts, continuation=run_analyzer):
  513. """ Execute only one phase of 2 phases of CTU if needed. """
  514. ctu_config = opts['ctu']
  515. if ctu_config.collect or ctu_config.analyze:
  516. assert ctu_config.collect != ctu_config.analyze
  517. if ctu_config.collect:
  518. return ctu_collect_phase(opts)
  519. if ctu_config.analyze:
  520. cwd = opts['directory']
  521. cmd = [opts['clang'], '--analyze'] + opts['direct_args'] \
  522. + opts['flags'] + [opts['file']]
  523. triarch = get_triple_arch(cmd, cwd)
  524. ctu_options = ['ctu-dir=' + os.path.join(ctu_config.dir, triarch),
  525. 'experimental-enable-naive-ctu-analysis=true']
  526. analyzer_options = prefix_with('-analyzer-config', ctu_options)
  527. direct_options = prefix_with('-Xanalyzer', analyzer_options)
  528. opts['direct_args'].extend(direct_options)
  529. return continuation(opts)
  530. @require(['flags', 'force_debug'])
  531. def filter_debug_flags(opts, continuation=dispatch_ctu):
  532. """ Filter out nondebug macros when requested. """
  533. if opts.pop('force_debug'):
  534. # lazy implementation just append an undefine macro at the end
  535. opts.update({'flags': opts['flags'] + ['-UNDEBUG']})
  536. return continuation(opts)
  537. @require(['language', 'compiler', 'file', 'flags'])
  538. def language_check(opts, continuation=filter_debug_flags):
  539. """ Find out the language from command line parameters or file name
  540. extension. The decision also influenced by the compiler invocation. """
  541. accepted = frozenset({
  542. 'c', 'c++', 'objective-c', 'objective-c++', 'c-cpp-output',
  543. 'c++-cpp-output', 'objective-c-cpp-output'
  544. })
  545. # language can be given as a parameter...
  546. language = opts.pop('language')
  547. compiler = opts.pop('compiler')
  548. # ... or find out from source file extension
  549. if language is None and compiler is not None:
  550. language = classify_source(opts['file'], compiler == 'c')
  551. if language is None:
  552. logging.debug('skip analysis, language not known')
  553. return None
  554. elif language not in accepted:
  555. logging.debug('skip analysis, language not supported')
  556. return None
  557. else:
  558. logging.debug('analysis, language: %s', language)
  559. opts.update({'language': language,
  560. 'flags': ['-x', language] + opts['flags']})
  561. return continuation(opts)
  562. @require(['arch_list', 'flags'])
  563. def arch_check(opts, continuation=language_check):
  564. """ Do run analyzer through one of the given architectures. """
  565. disabled = frozenset({'ppc', 'ppc64'})
  566. received_list = opts.pop('arch_list')
  567. if received_list:
  568. # filter out disabled architectures and -arch switches
  569. filtered_list = [a for a in received_list if a not in disabled]
  570. if filtered_list:
  571. # There should be only one arch given (or the same multiple
  572. # times). If there are multiple arch are given and are not
  573. # the same, those should not change the pre-processing step.
  574. # But that's the only pass we have before run the analyzer.
  575. current = filtered_list.pop()
  576. logging.debug('analysis, on arch: %s', current)
  577. opts.update({'flags': ['-arch', current] + opts['flags']})
  578. return continuation(opts)
  579. else:
  580. logging.debug('skip analysis, found not supported arch')
  581. return None
  582. else:
  583. logging.debug('analysis, on default arch')
  584. return continuation(opts)
  585. # To have good results from static analyzer certain compiler options shall be
  586. # omitted. The compiler flag filtering only affects the static analyzer run.
  587. #
  588. # Keys are the option name, value number of options to skip
  589. IGNORED_FLAGS = {
  590. '-c': 0, # compile option will be overwritten
  591. '-fsyntax-only': 0, # static analyzer option will be overwritten
  592. '-o': 1, # will set up own output file
  593. # flags below are inherited from the perl implementation.
  594. '-g': 0,
  595. '-save-temps': 0,
  596. '-install_name': 1,
  597. '-exported_symbols_list': 1,
  598. '-current_version': 1,
  599. '-compatibility_version': 1,
  600. '-init': 1,
  601. '-e': 1,
  602. '-seg1addr': 1,
  603. '-bundle_loader': 1,
  604. '-multiply_defined': 1,
  605. '-sectorder': 3,
  606. '--param': 1,
  607. '--serialize-diagnostics': 1
  608. }
  609. def classify_parameters(command):
  610. """ Prepare compiler flags (filters some and add others) and take out
  611. language (-x) and architecture (-arch) flags for future processing. """
  612. result = {
  613. 'flags': [], # the filtered compiler flags
  614. 'arch_list': [], # list of architecture flags
  615. 'language': None, # compilation language, None, if not specified
  616. 'compiler': compiler_language(command) # 'c' or 'c++'
  617. }
  618. # iterate on the compile options
  619. args = iter(command[1:])
  620. for arg in args:
  621. # take arch flags into a separate basket
  622. if arg == '-arch':
  623. result['arch_list'].append(next(args))
  624. # take language
  625. elif arg == '-x':
  626. result['language'] = next(args)
  627. # parameters which looks source file are not flags
  628. elif re.match(r'^[^-].+', arg) and classify_source(arg):
  629. pass
  630. # ignore some flags
  631. elif arg in IGNORED_FLAGS:
  632. count = IGNORED_FLAGS[arg]
  633. for _ in range(count):
  634. next(args)
  635. # we don't care about extra warnings, but we should suppress ones
  636. # that we don't want to see.
  637. elif re.match(r'^-W.+', arg) and not re.match(r'^-Wno-.+', arg):
  638. pass
  639. # and consider everything else as compilation flag.
  640. else:
  641. result['flags'].append(arg)
  642. return result